Skip to content

Commit 417ec8a

Browse files
authored
Create main.py
1 parent 3a77b72 commit 417ec8a

File tree

1 file changed

+100
-0
lines changed
  • convolutional_neural_network

1 file changed

+100
-0
lines changed

convolutional_neural_network/main.py

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import torch
2+
import torch.nn as nn
3+
import torchvision
4+
import torchvision.transforms as transforms
5+
6+
7+
# Device configuration
8+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
9+
10+
# Hyper parameters
11+
num_epochs = 5
12+
num_classes = 10
13+
batch_size = 100
14+
learning_rate = 0.001
15+
16+
# MNIST dataset
17+
train_dataset = torchvision.datasets.MNIST(root='../../data/',
18+
train=True,
19+
transform=transforms.ToTensor(),
20+
download=True)
21+
22+
test_dataset = torchvision.datasets.MNIST(root='../../data/',
23+
train=False,
24+
transform=transforms.ToTensor())
25+
26+
# Data loader
27+
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
28+
batch_size=batch_size,
29+
shuffle=True)
30+
31+
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
32+
batch_size=batch_size,
33+
shuffle=False)
34+
35+
# Convolutional neural network (two convolutional layers)
36+
class ConvNet(nn.Module):
37+
def __init__(self, num_classes=10):
38+
super(ConvNet, self).__init__()
39+
self.layer1 = nn.Sequential(
40+
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
41+
nn.BatchNorm2d(16),
42+
nn.ReLU(),
43+
nn.MaxPool2d(kernel_size=2, stride=2))
44+
self.layer2 = nn.Sequential(
45+
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
46+
nn.BatchNorm2d(32),
47+
nn.ReLU(),
48+
nn.MaxPool2d(kernel_size=2, stride=2))
49+
self.fc = nn.Linear(7*7*32, num_classes)
50+
51+
def forward(self, x):
52+
out = self.layer1(x)
53+
out = self.layer2(out)
54+
out = out.reshape(out.size(0), -1)
55+
out = self.fc(out)
56+
return out
57+
58+
model = ConvNet(num_classes).to(device)
59+
60+
# Loss and optimizer
61+
criterion = nn.CrossEntropyLoss()
62+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
63+
64+
# Train the model
65+
total_step = len(train_loader)
66+
for epoch in range(num_epochs):
67+
for i, (images, labels) in enumerate(train_loader):
68+
images = images.to(device)
69+
labels = labels.to(device)
70+
71+
# Forward pass
72+
outputs = model(images)
73+
loss = criterion(outputs, labels)
74+
75+
# Backward and optimize
76+
optimizer.zero_grad()
77+
loss.backward()
78+
optimizer.step()
79+
80+
if (i+1) % 100 == 0:
81+
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
82+
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
83+
84+
# Test the model
85+
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
86+
with torch.no_grad():
87+
correct = 0
88+
total = 0
89+
for images, labels in test_loader:
90+
images = images.to(device)
91+
labels = labels.to(device)
92+
outputs = model(images)
93+
_, predicted = torch.max(outputs.data, 1)
94+
total += labels.size(0)
95+
correct += (predicted == labels).sum().item()
96+
97+
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
98+
99+
# Save the model checkpoint
100+
torch.save(model.state_dict(), 'model.ckpt')

0 commit comments

Comments
 (0)