-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredict.py
175 lines (111 loc) · 4.61 KB
/
predict.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# Imports
import torch
import numpy as np
import torchvision
from torch import optim
import matplotlib.pyplot as plt
from torchvision import datasets, transforms, models
from collections import OrderedDict
import helper_functions
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#Load Data
data_dir = 'flowers'
test_dir = data_dir + '/test'
# Load the datasets with ImageFolder
image_datasets = helper_functions.load_datasets()
test_data = image_datasets['test']
# DataLoaders
dataloaders = helper_functions.load_dataloaders()
testloader = dataloaders['test']
# from train import data_transforms['test']
# from train import image_datasets['test']
# from train import dataloaders['test']
load_model = helper_functions.load_checkpoint('checkpoint.pth')
def predict_or_not():
answer= input("Would you like to make predictions?[y, n ]\n")
helper_functions.vaildating_input(answer)
if answer =='y':
image_path= input("May you provide the directory of the image along with the image you would like to predict on\n")
print("Working on it..........\n")
predict(image_path)
# predict(image_path,load_model, class_dict=helper_functions.load_labels())
print("Showing results........\n")
sanity_check(image_path, load_model)
elif answer =='n':
print("Thanks for your time, Exiting.........")
def process_image(image_path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Loading the image using PIL liberary
imageFile = torchvision.io.read_image(str(image_path)).type(torch.float32)/255.
image_transform = transforms.Compose([transforms.Resize(224),
transforms.CenterCrop(224),
# transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
processed_image = image_transform(imageFile)
return processed_image
def imshow(image, ax=None, title=None):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.numpy().transpose((1, 2, 0))
# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
ax.imshow(image)
ax.axis(False)
plt.show();
return ax
# def predict(image_path, topk, model=load_model, class_dict=helper_functions.load_labels(), device= device ):
def predict(image_path, model=load_model, class_dict=helper_functions.load_labels(), device= device, topk =5):
"""
Pass an image path and let the model make predictions on that image and plot the image and the 5 top predictions
"""
model.to(device)
# Load the image
image = process_image(image_path)
# Making predictions
model.eval()
with torch.inference_mode():
img = image.unsqueeze(0)
img = img.to(device)
logit = model(img)
ps = torch.exp(logit)
top_k_probs, top_k_class = ps.topk(topk, dim=1)
top_k_probs = top_k_probs[0]
top_k_class = top_k_class[0]
top_class_titles=[]
for i in range(len(top_k_class)):
for k,v in class_dict.items():
if v == top_k_class[i]:
top_class_titles.append(k)
return top_k_probs, top_class_titles
def sanity_check(image_path, model=load_model):
# model= load_checkpoint('checkpoint.pth')
image = process_image(image_path)
probs,classes = predict(image_path, load_model)
probs = probs.cpu()
fig = plt.figure(figsize =[9,9])
plot1 = plt.subplot(4,4,2)
plot2 = plt.subplot(4,1,2)
plot1.axis('off')
plot1.set_title(classes[0])
plot1.imshow(image.permute(2,1,0))
y_ticks = np.arange(5)
plot2.set_yticks(y_ticks)
plot2.set_yticklabels(classes)
plot2.barh(y_ticks, probs)
plt.show()
print("\n")
print("\n")
print("The top most probable classes along with their probabilities are :\n")
for i in range(len(classes)):
print(f" Class {i+1} is : {classes[i]} | with probability {probs[i]}\n")