dhkim2810 commited on
Commit
17c015f
·
1 Parent(s): 5421186

MNIST practice

Browse files
Files changed (2) hide show
  1. app.py +55 -0
  2. ckpt.pth +3 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import torch.optim as optim
7
+ from PIL import Image
8
+ from torchvision import transforms
9
+
10
+
11
+ class simpleCNN(nn.Module):
12
+ def __init__(self, num_classes=3):
13
+ super(simpleCNN, self).__init__()
14
+ self.name = "simpleCNN"
15
+ self.conv1 = nn.Conv2d(3, 5, 5)
16
+ self.pool = nn.MaxPool2d(2, 2)
17
+ self.conv2 = nn.Conv2d(5, 10, 5)
18
+ self.fc1 = nn.Linear(10 * 5 * 5, 32)
19
+ self.fc2 = nn.Linear(32, num_classes)
20
+
21
+ def forward(self, x):
22
+ x = self.pool(F.relu(self.conv1(x)))
23
+ x = self.pool(F.relu(self.conv2(x)))
24
+ x = x.view(-1, 10 * 5 * 5)
25
+ x = F.relu(self.fc1(x))
26
+ x = self.fc2(x)
27
+ return x
28
+
29
+
30
+ net = simpleCNN(num_classes=3)
31
+ net.load_state_dict(torch.load("./ckpt.pth", map_location=torch.device("cpu")))
32
+ net.eval()
33
+ class_labels = ["other", "car", "truck"]
34
+
35
+ transform = transforms.Compose(
36
+ [
37
+ transforms.Resize((32, 32)),
38
+ transforms.ToTensor(),
39
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
40
+ ]
41
+ )
42
+
43
+
44
+ @torch.no_grad()
45
+ def predict(img):
46
+ global net
47
+ img = Image.fromarray(img.astype("uint8"), "RGB")
48
+ img = transform(img).unsqueeze(0)
49
+ pred = net(img).detach().numpy()[0]
50
+ pred = np.exp(pred) / np.sum(np.exp(pred))
51
+ return {class_labels[i]: float(pred[i]) for i in range(len(class_labels))}
52
+
53
+
54
+ iface = gr.Interface(fn=predict, inputs="image", outputs="label")
55
+ iface.launch()
ckpt.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d76475d89dc4b7a811eebff3dfb1f12e207534a4281c58d9dd110e7117aee9b
3
+ size 41457