Torch - nn

For PyTorch to track operations, you need to wrap a tensor with the Variable.

You can get the tensor back with the .data attribute of the Variable.

The gradients are computed with respect to some variable zwith z.backward().

Train

import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms

# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                              transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
                             ])
# Download and load the training data
trainset = datasets.MNIST('MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

# Download and load the test data
testset = datasets.MNIST('MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)

Epoch: 1/1 Loss: 2.1246 Test accuracy: 0.4726

Epoch: 1/1 Loss: 1.5973 Test accuracy: 0.5754

Epoch: 1/1 Loss: 1.2325 Test accuracy: 0.7483

Epoch: 1/1 Loss: 0.9512 Test accuracy: 0.7622

Test

Last updated

Was this helpful?