1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms from PIL import Image from sklearn import preprocessing import os import time
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("device:", device)
class NotMinstDataset(Dataset): def __init__(self, file_dir): self.imgs = [] labels = [] for root, sub_folders, files in os.walk(file_dir): for name in files: self.imgs.append(os.path.join(root, name)) labels.append(root.split("\\")[1]) le = preprocessing.LabelEncoder() self.targets = le.fit_transform(labels) self.targets = torch.as_tensor(self.targets)
def __getitem__(self, index): img = self.imgs[index] label = self.targets[index] img = Image.open(img) img = self.img_transform(img)
return img, label
def __len__(self): return len(self.imgs)
def img_transform(self, img): transform = transforms.Compose( [ transforms.ToTensor(), ] ) img = transform(img) return img
def data(train=True): dataset = NotMinstDataset("./notMNIST_small") train_size = int(0.8 * len(dataset)) test_size = len(dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size]) if train: loader = DataLoader(train_dataset, batch_size=64, shuffle=True) else: loader = DataLoader(test_dataset, batch_size=64, shuffle=True) return loader
class Net(nn.Module):
def __init__(self): super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5, 1, padding=2) self.conv2 = nn.Conv2d(6, 16, 5, 1)
self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)
def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) x = x.view(x.size(0), -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
net = Net().to(device) criterion = nn.CrossEntropyLoss().to(device) optimizer = optim.Adam(net.parameters(), lr=0.001)
trainloader = data(True) testloader = data(False) t0 = time.time()
for epoch in range(1): running_loss = 0.0 for batch_idx, (input, label) in enumerate(trainloader): input, label = input.to(device), label.to(device).squeeze() optimizer.zero_grad() output = net(input) loss = criterion(output, label) loss.backward() optimizer.step()
running_loss += loss.item()
if batch_idx % 100 == 99: print('[%d, %5d] loss: %.10f' % (epoch + 1, batch_idx + 1, running_loss / 100)) running_loss = 0.0 print('{} seconds'.format(time.time() - t0))
correct = 0 total = 0 with torch.no_grad(): for batch_idx, (input, label) in enumerate(testloader): input, label = input.to(device), label.to(device) outputs = net(input) _, predicted = torch.max(outputs.data, 1) total += label.size(0) correct += (predicted == label).sum().item()
print('Accuracy of the network on the test images: %.10f %%' % (100 * correct / total))
|