Skip to content

Instantly share code, notes, and snippets.

@jcdevilleres
Last active June 4, 2020 11:30
Show Gist options
  • Save jcdevilleres/2f238a36a4638743602901dcf17285fe to your computer and use it in GitHub Desktop.
Save jcdevilleres/2f238a36a4638743602901dcf17285fe to your computer and use it in GitHub Desktop.
Quick start: PyTorch, Training Classifier - Neutral Network
# Import libraries required for neutral network
import torch
# Vision-specific library which will contain our dataset and help us define how our images are loaded
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
# Create image transform when we load the dataset of PIL images
transform = transforms.Compose(
[transforms.ToTensor(), #Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Normalize a tensor image with mean and standard deviation.
# Load of of the prepared datasets and define train (create training dataset), transform (function to transform our PIL images), and others
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=8,
shuffle=True, num_workers=2)
# Re-do same procedure for our test set
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=8,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# notice that the labels variable is a tensor with index for each class
labels
# images is a tensor-type object of length 8
print(type(images), len(images))
# Repeat the same for our test data
dataiter = iter(testloader)
imagestest, labelstest = dataiter.next()
imshow(torchvision.utils.make_grid(imagestest))
print(','.join('%5s' % classes[labelstest[j]] for j in range(8)))
# loss function which is to be used in evaluating our model
criterion = nn.CrossEntropyLoss()
# define optimizer parameters
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(3): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize use our neural network class
outputs = net(inputs)
# we use our nn.CrossEntropyLoss()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
print('Note: look carefully at the loss pattern of each for loop and epoch')
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment