import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
SGD_loss = []
train_dataset = torchvision.datasets.MNIST(root='data/',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = torchvision.datasets.MNIST(root='data/',
train=False,
transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Sequential(nn.Linear(input_size, hidden_size),
nn.ReLU())
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.fc2(out)
return out
model = NeuralNet(input_size, hidden_size, num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1, 28 * 28)
outputs = model(images)
loss = criterion(outputs, labels)
SGD_loss.append(loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i + 1, total_step, loss.item()))
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28 * 28)
outputs = model(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: {} %'.format(100 * correct / total))
Epoch [1/5], Step [100/600], Loss: 2.2769
Epoch [1/5], Step [200/600], Loss: 2.2770
Epoch [1/5], Step [300/600], Loss: 2.2553
Epoch [1/5], Step [400/600], Loss: 2.2327
Epoch [1/5], Step [500/600], Loss: 2.2199
Epoch [1/5], Step [600/600], Loss: 2.1841
Epoch [2/5], Step [100/600], Loss: 2.1550
Epoch [2/5], Step [200/600], Loss: 2.1324
Epoch [2/5], Step [300/600], Loss: 2.0896
Epoch [2/5], Step [400/600], Loss: 2.0818
Epoch [2/5], Step [500/600], Loss: 2.0478
Epoch [2/5], Step [600/600], Loss: 2.0630
Epoch [3/5], Step [100/600], Loss: 2.0151
Epoch [3/5], Step [200/600], Loss: 2.0137
Epoch [3/5], Step [300/600], Loss: 1.9326
Epoch [3/5], Step [400/600], Loss: 1.8756
Epoch [3/5], Step [500/600], Loss: 1.8812
Epoch [3/5], Step [600/600], Loss: 1.8286
Epoch [4/5], Step [100/600], Loss: 1.7895
Epoch [4/5], Step [200/600], Loss: 1.7809
Epoch [4/