-
Notifications
You must be signed in to change notification settings - Fork 8
/
cnn_model.py
52 lines (48 loc) · 1.52 KB
/
cnn_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvNN(nn.Module):
def __init__(
self,
num_filters: int = 32,
kernel_size: int = 4,
dense_layer: int = 128,
img_rows: int = 28,
img_cols: int = 28,
maxpool: int = 2,
):
"""
Basic Architecture of CNN
Attributes:
num_filters: Number of filters, out channel for 1st and 2nd conv layers,
kernel_size: Kernel size of convolution,
dense_layer: Dense layer units,
img_rows: Height of input image,
img_cols: Width of input image,
maxpool: Max pooling size
"""
super(ConvNN, self).__init__()
self.conv1 = nn.Conv2d(1, num_filters, kernel_size, 1)
self.conv2 = nn.Conv2d(num_filters, num_filters, kernel_size, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(
num_filters
* ((img_rows - 2 * kernel_size + 2) // 2)
* ((img_cols - 2 * kernel_size + 2) // 2),
dense_layer,
)
self.fc2 = nn.Linear(dense_layer, 10)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
out = self.fc2(x)
return out