-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcnn.py
48 lines (37 loc) · 1.59 KB
/
cnn.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
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class CNN(nn.Module):
def __init__(self, name, input_channels, output_channels, output_dim):
super(CNN, self).__init__()
self.name = name
self.conv1 = nn.Conv2d(input_channels, output_channels, kernel_size=11, padding=1).to(device)
self.conv2 = nn.Conv2d(output_channels, output_channels, kernel_size=3, padding=1).to(device)
self.conv3 = nn.Conv2d(output_channels, output_channels, kernel_size=3, padding=1).to(device)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.relu = nn.ReLU(inplace=True)
self.fc = nn.Linear(output_channels * 30 * 30, output_dim)
self.sm = nn.Softmax(dim=1)
self.initialize_weights()
def initialize_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
# init random weights
nn.init.kaiming_normal_(module.weight)
# init random bias
if module.bias is not None:
module.bias.data.zero_()
def __str__(self):
return f"{self.name} CNN model"
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv3(x) # Applying the third Conv2d layer
x = self.relu(x)
x = self.pool(x)
output = self.fc(torch.flatten(x, start_dim=1))
return self.sm(output)