-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInceptionV3 Predict.py
125 lines (98 loc) · 4.14 KB
/
InceptionV3 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
# -*- coding: utf-8 -*-
"""iv3_predict.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1473B_s_fi8sM-v3khcv_pAYvCbjkoi_k
"""
from google.colab import drive
drive.mount('/content/drive')
#
# **************************************************************************************************************************************************
# Libraries
# **************************************************************************************************************************************************
#
import datetime
import numpy as np
import os
import pandas as pd
from keras import applications
from keras import optimizers
from keras.models import Model
from keras.layers import Flatten, Dense
from keras.preprocessing.image import image, ImageDataGenerator
np.random.seed(1337)
#
# **************************************************************************************************************************************************
# Global Variables
# **************************************************************************************************************************************************
#
# location of the test image
imagePath = '/content/drive/My Drive/Dataset/data/test/Benign/2_15.jpg'
# saved filename of model weights
weights_filename = '/content/drive/My Drive/FYP/model_checkpoint.h5'
# saved filename of result csv
results_filename = '/content/drive/My Drive/FYP/results.csv'
# directories of dataset
test_data_dir = '/content/drive/My Drive/Dataset/data/test'
# dimensions of the architecture
img_width, img_height = 299, 299
# number of channels for the architecture
channels = 3
# learning rate
learning_rate = 1e-4
# class mode
class_mode = 'categorical'
# total number of classes
total_classes = 2
#
# **************************************************************************************************************************************************
# Main Code
# **************************************************************************************************************************************************
#
model = applications.InceptionV3(include_top = False, weights = 'imagenet', classes = total_classes, input_shape = (img_width, img_height, channels))
flat = Flatten()(model.layers[-1].output)
output = Dense(total_classes, activation = "softmax")(flat)
loaded_model = Model(inputs = model.inputs, outputs = output)
loaded_model.compile(loss = 'categorical_crossentropy', optimizer = optimizers.SGD(lr = learning_rate), metrics = ['acc'])
loaded_model.load_weights(weights_filename, by_name = True)
# predict single test image
def test_image(path, output):
test_image = image.load_img(path, target_size = (299, 299))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = loaded_model.predict(test_image)
confidence = ["{:.10f}".format(r) for r in result[0]]
if output: print("Confidence: ", confidence)
if (result[0][0] == result[0][1]):
if output: print("Thyroid Type: Unknown. Unable to classify this image.")
return "Unknown", confidence
elif (np.argmax(result, axis = 1) == 0):
if output: print("Thyroid Type: Benign")
return "Benign", confidence
else:
if output: print("Thyroid Type: Malignant")
return "Malignant", confidence
# predict one image
test_image(imagePath, True)
# predict all test images
images = []
predictions = []
confidences = []
print("Predicting all test images..")
start = datetime.datetime.now()
count = 0
for (dirpath, dirnames, filenames) in os.walk(test_data_dir):
for file in filenames:
result, confidence = test_image(os.path.join(dirpath, file), False)
images.append(file)
predictions.append(result)
confidences.append(confidence)
count += 1
print("Writing " + str(count) + " results to CSV..")
results = pd.DataFrame({"Filename": images,
"Prediction": predictions,
"Confidence": confidences})
results.to_csv(results_filename, index = False)
end = datetime.datetime.now()
elapsed = end - start
print("Prediction completed after " + str(elapsed) + ".")