-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombined.py
141 lines (110 loc) · 4.2 KB
/
combined.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# Imports
import torch
from torchvision import transforms
import torch.nn as nn
import torch.nn.functional as F
from tkinter import *
from PIL import Image, ImageDraw
values = list()
# init of the neural net
# DON'T INCLUDE TRAINING HERE
# Training is done with the trainer.py file
class Net(nn.Module):
# make sure to include the fact that this was taken from pytorch documentation ###########################
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(28*28, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, 64)
self.fc4 = nn.Linear(64, 10)
# make sure to include the fact that this was taken from pytorch documentation######################################
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return F.log_softmax(x, dim=1)
# Saves the canvas and converts it into 28x28, so it is readable by the program.
def save():
image.save("image.png")
img = Image.open("image.png")
resized_img = img.resize((28,28))
resized_img.save("resized.png")
# Takes the 28x28 png file and evaluates it. It imports an existing neural net model that was
# created by the 'trainer.py' file
def evaluate():
save()
img = Image.open("resized.png")
path = "model/training.pt"
model = Net()
model.load_state_dict(torch.load(path))
model.eval()
# test
transform = transforms.ToTensor()
tensor_array = transform(img) # Tensor
with torch.no_grad():
x = tensor_array
output = model(x.view(-1,784))
for i in enumerate(output):
widget = Label(canvas, text=f'Predicted: {torch.argmax(i[1])}', fg='black', bg='white')
widget.place(x=5,y=280)
print(torch.argmax(i[1])) # Should print out what number it thinks.
# Saves a list of all predicted numbers for the "info" function
global values
values = i[1].tolist()
break
# Drawing function, also auto-evaluates
def draw(arg):
x,y,x1,y1 = (arg.x-1), (arg.y-1), (arg.x+1), (arg.y+1)
canvas.create_oval(x,y,x1,y1, fill="white",width=30)
draw.line([x,y,x1,y1],fill="white",width=30)
evaluate() # Can remove so that it doesn't evaluate for each new pixel drawn
# Draws a (white) black rectangle over the entire canvas, erasing all contents.
def clear():
canvas.delete("all")
draw.rectangle((0,0,500,500),"black")
save()
# More Info Button
# Returns extra info on the evaluation. Returns other possibilities.
def info():
fixed = dict()
final = dict()
# rounds each neuron value
for i in range(len(values)):
temp = round(values[i],2)
values[i] = temp
# assigns numeric value to appropriate value
# returns a dict {"0.1231" = 1}
for i in range(len(values)):
ind = values[i]
fixed[f"{ind}"] = i
# sort the list greatest -> least
values.sort(reverse=True)
for i in values:
temp = fixed[f"{i}"]
final[i]=temp
#print(final,values)
formattedTxt = str()
formattedTxt = formattedTxt+"Values closest to 0 represent its confidence.\n"
for i in final:
# symbol fix
if i == 0:
formattedTxt = formattedTxt+f'\n"{final[i]}" -> {i}'
else:
formattedTxt = formattedTxt+f'\n"{final[i]}" -> ±{i*-1}'
# Creates a new window that displays the new values
newWindow = Toplevel(app)
newWindow.title("More info")
newWindow.geometry("250x200")
Label(newWindow,text =f"{formattedTxt}").pack()
# Declarations of the GUI
width, height = 300,300
app = Tk()
canvas = Canvas(app,bg="white",width=width,height=height)
canvas.pack(expand=YES,fill=BOTH)
canvas.bind("<B1-Motion>", draw)
image = Image.new("RGB", (width,height), (0,0,0))
draw = ImageDraw.Draw(image)
button=Button(text="More Info",command=info).pack()
button=Button(text="Clear",command=clear).pack()
app.mainloop() # Make sure to always include this at end, GUIs cannot function without it.