Anni0401 commited on
Commit
6d70e98
·
verified ·
1 Parent(s): 7be60c5

Add MNIST CNN model and inference code

Browse files
Files changed (1) hide show
  1. cnn.py +36 -0
cnn.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class MNISTCNN(nn.Module):
7
+ """
8
+ Convolutional Neural Network for MNIST classification.
9
+ """
10
+
11
+ def __init__(self):
12
+ super().__init__()
13
+
14
+ # Feature extractor
15
+ self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
16
+ self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
17
+
18
+ self.pool = nn.MaxPool2d(2, 2)
19
+
20
+ # Classifier
21
+ self.fc1 = nn.Linear(64 * 7 * 7, 128)
22
+ self.dropout = nn.Dropout(p=0.5)
23
+ self.fc2 = nn.Linear(128, 10)
24
+
25
+ def forward(self, x):
26
+ # x: [batch_size, 1, 28, 28]
27
+
28
+ x = self.pool(F.relu(self.conv1(x))) # -> [B, 32, 14, 14]
29
+ x = self.pool(F.relu(self.conv2(x))) # -> [B, 64, 7, 7]
30
+
31
+ x = x.view(x.size(0), -1) # Flatten
32
+ x = F.relu(self.fc1(x))
33
+ x = self.dropout(x)
34
+ x = self.fc2(x) # Logits
35
+
36
+ return x