Create model.py
Browse files
model.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from huggingface_hub import hf_hub_download
|
4 |
+
|
5 |
+
|
6 |
+
class SimpleCNN(nn.Module):
|
7 |
+
def __init__(self, num_classes=6):
|
8 |
+
super(SimpleCNN, self).__init__()
|
9 |
+
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
|
10 |
+
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
|
11 |
+
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
|
12 |
+
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
|
13 |
+
self.relu = nn.ReLU()
|
14 |
+
self.dropout = nn.Dropout(0.5)
|
15 |
+
self._initialize_fc(num_classes)
|
16 |
+
|
17 |
+
def _initialize_fc(self, num_classes):
|
18 |
+
dummy_input = torch.zeros(1, 3, 448, 448)
|
19 |
+
x = self.pool(self.relu(self.conv1(dummy_input)))
|
20 |
+
x = self.pool(self.relu(self.conv2(x)))
|
21 |
+
x = self.pool(self.relu(self.conv3(x)))
|
22 |
+
x = x.view(x.size(0), -1)
|
23 |
+
flattened_size = x.shape[1]
|
24 |
+
self.fc1 = nn.Linear(flattened_size, 512)
|
25 |
+
self.fc2 = nn.Linear(512, num_classes)
|
26 |
+
|
27 |
+
def forward(self, x):
|
28 |
+
x = self.pool(self.relu(self.conv1(x)))
|
29 |
+
x = self.pool(self.relu(self.conv2(x)))
|
30 |
+
x = self.pool(self.relu(self.conv3(x)))
|
31 |
+
x = x.view(x.size(0), -1)
|
32 |
+
x = self.dropout(self.relu(self.fc1(x)))
|
33 |
+
x = self.fc2(x)
|
34 |
+
return x
|
35 |
+
|
36 |
+
def load_model(device: str = 'cpu'):
|
37 |
+
"""
|
38 |
+
Downloads and loads the pretrained SimpleCNN model for the 'c' version.
|
39 |
+
"""
|
40 |
+
torch_device = torch.device(device)
|
41 |
+
|
42 |
+
weights_path = hf_hub_download(
|
43 |
+
repo_id="Neurazum/Vbai-DPA-2.3",
|
44 |
+
filename="Vbai-DPA 2.3c.pt",
|
45 |
+
repo_type="model"
|
46 |
+
)
|
47 |
+
|
48 |
+
model = SimpleCNN(num_classes=6).to(torch_device)
|
49 |
+
state = torch.load(weights_path, map_location=torch_device)
|
50 |
+
model.load_state_dict(state)
|
51 |
+
model.eval()
|
52 |
+
return model
|