Skip to content

Commit 00657e4

Browse files
committed
added 13
1 parent ba42a95 commit 00657e4

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

13_feedforward.py

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import torch
2+
import torch.nn as nn
3+
import torchvision
4+
import torchvision.transforms as transforms
5+
import matplotlib.pyplot as plt
6+
7+
# Device configuration
8+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9+
10+
# Hyper-parameters
11+
input_size = 784 # 28x28
12+
hidden_size = 500
13+
num_classes = 10
14+
num_epochs = 2
15+
batch_size = 100
16+
learning_rate = 0.001
17+
18+
# MNIST dataset
19+
train_dataset = torchvision.datasets.MNIST(root='./data',
20+
train=True,
21+
transform=transforms.ToTensor(),
22+
download=True)
23+
24+
test_dataset = torchvision.datasets.MNIST(root='./data',
25+
train=False,
26+
transform=transforms.ToTensor())
27+
28+
# Data loader
29+
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
30+
batch_size=batch_size,
31+
shuffle=True)
32+
33+
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
34+
batch_size=batch_size,
35+
shuffle=False)
36+
37+
examples = iter(test_loader)
38+
example_data, example_targets = examples.next()
39+
40+
for i in range(6):
41+
plt.subplot(2,3,i+1)
42+
plt.imshow(example_data[i][0], cmap='gray')
43+
plt.show()
44+
45+
# Fully connected neural network with one hidden layer
46+
class NeuralNet(nn.Module):
47+
def __init__(self, input_size, hidden_size, num_classes):
48+
super(NeuralNet, self).__init__()
49+
self.input_size = input_size
50+
self.l1 = nn.Linear(input_size, hidden_size)
51+
self.relu = nn.ReLU()
52+
self.l2 = nn.Linear(hidden_size, num_classes)
53+
54+
def forward(self, x):
55+
out = self.l1(x)
56+
out = self.relu(out)
57+
out = self.l2(out)
58+
# no activation and no softmax at the end
59+
return out
60+
61+
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
62+
63+
# Loss and optimizer
64+
criterion = nn.CrossEntropyLoss()
65+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
66+
67+
# Train the model
68+
n_total_steps = len(train_loader)
69+
for epoch in range(num_epochs):
70+
for i, (images, labels) in enumerate(train_loader):
71+
# origin shape: [100, 1, 28, 28]
72+
# resized: [100, 784]
73+
images = images.reshape(-1, 28*28).to(device)
74+
labels = labels.to(device)
75+
76+
# Forward pass
77+
outputs = model(images)
78+
loss = criterion(outputs, labels)
79+
80+
# Backward and optimize
81+
optimizer.zero_grad()
82+
loss.backward()
83+
optimizer.step()
84+
85+
if (i+1) % 100 == 0:
86+
print (f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}')
87+
88+
# Test the model
89+
# In test phase, we don't need to compute gradients (for memory efficiency)
90+
with torch.no_grad():
91+
n_correct = 0
92+
n_samples = 0
93+
for images, labels in test_loader:
94+
images = images.reshape(-1, 28*28).to(device)
95+
labels = labels.to(device)
96+
outputs = model(images)
97+
# max returns (value ,index)
98+
_, predicted = torch.max(outputs.data, 1)
99+
n_samples += labels.size(0)
100+
n_correct += (predicted == labels).sum().item()
101+
102+
acc = 100.0 * n_correct / n_samples
103+
print(f'Accuracy of the network on the 10000 test images: {acc} %')

0 commit comments

Comments
 (0)