-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
57 lines (49 loc) · 1.89 KB
/
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
53
54
55
56
57
# 以下を「model.py」に書き込み
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models, transforms
from PIL import Image
classes_ja = ["飛行機", "自動車", "鳥", "猫", "鹿", "犬", "カエル", "馬", "船", "トラック"]
classes_en = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
n_class = len(classes_ja)
img_size = 32
# CNNのモデル
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 256)
self.dropout = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16*5*5)
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
def predict(img):
# モデルへの入力
img = img.convert("RGB")
img = img.resize((img_size, img_size))
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)) # 平均値を0、標準偏差を1に
])
img = transform(img)
x = img.reshape(1, 3, img_size, img_size)
# 訓練済みモデル
net = Net()
net.load_state_dict(torch.load(
"model_cnn.pth", map_location=torch.device("cpu")
))
# 予測
net.eval()
y = net(x)
# 結果を返す
y_prob = torch.nn.functional.softmax(torch.squeeze(y)) # 確率で表す
sorted_prob, sorted_indices = torch.sort(y_prob, descending=True) # 降順にソート
return [(classes_ja[idx], classes_en[idx], prob.item()) for idx, prob in zip(sorted_indices, sorted_prob)]