-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_models.py
229 lines (158 loc) · 7.64 KB
/
test_models.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import os
import random
import datetime
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from time import perf_counter
from random import randrange
from PIL import Image
undetermined_range = 15
def getModelAccuracy(predictions, anwser_sheet):
right = 0
wrong = 0
undetermined = 0
for prediction, anwser in zip(predictions, anwser_sheet):
if abs(prediction[0]) < undetermined_range:
undetermined = undetermined + 1
elif prediction[0] > undetermined_range and anwser == 1:
right = right + 1
elif prediction[0] < -undetermined_range and anwser == 0:
right = right + 1
elif prediction[0] > undetermined_range and anwser == 0:
wrong = wrong + 1
elif prediction[0] < -undetermined_range and anwser == 1:
wrong = wrong + 1
rate = 0
if (right + wrong) != 0:
rate = (right / (right + wrong)) * 100
return rate, undetermined, right, wrong
def getAccuracyTag(prediction, anwser):
if abs(prediction[0]) < undetermined_range:
return "undetermined"
elif prediction[0] > undetermined_range and anwser == 1:
return "right"
elif prediction[0] < -undetermined_range and anwser == 0:
return "right"
elif prediction[0] > undetermined_range and anwser == 0:
return "wrong"
elif prediction[0] < -undetermined_range and anwser == 1:
return "wrong"
def getAnwserTag(number):
if number == 0:
return "cancer_positive"
else:
return "cancer_negitive"
def getFileExtenstion(filename):
file_name_parts = filename.split(".")
return file_name_parts[len(file_name_parts)-1].lower()
images_to_classify_dirs = [["cleaned_dataset_test/cancer", "cancer"], ["cleaned_dataset_test/no_cancer", "not_cancer"]]
models_folder = "models_to_test"
reso = (256, 256)
invalid_images = 0
models = []
model_names = []
unloaded_models = []
images_list = []
image_list_names = []
# build models
for model_filename in os.listdir(models_folder):
try:
model = tf.keras.models.load_model(os.path.join(models_folder, model_filename))
models.append(model)
model_names.append(os.path.splitext(model_filename)[0])
print(f"{model_filename} loaded!")
except:
print(f"{model_filename} couldn't be loaded.")
unloaded_models.append(os.path.join(models_folder, model_filename))
# load_images
print("\nLoading images...\n")
for folder_count, directory in enumerate(images_to_classify_dirs):
folder_count = folder_count + 1
amount_of_images = len(os.listdir(directory[0]))
for count, filename in enumerate(os.listdir(directory[0])):
count = count + 1
filepath = 0
image = 0
try:
filepath = os.path.join(directory[0], filename)
image = Image.open(filepath)
except:
invalid_images += 1
print(f"{filepath} invalid. [{amount_of_images - count} images remaining]")
continue
if getFileExtenstion(filename) != "jpg":
if getFileExtenstion(filename) != "png":
if getFileExtenstion(filename) != "jpeg":
invalid_images += 1
print(f"{filepath} invalid. (file-type invalid) [{amount_of_images - count} images remaining]")
continue
if image.size[0] != reso[0] or image.size[1] != reso[1] or image.mode != "RGB":
invalid_images += 1
print(f"{filepath} invalid. (resultion different or color mode non-RGB) [{amount_of_images - count} images remaining]")
continue
image_list = []
for x in range(image.size[0]):
row = []
for y in range(image.size[1]):
row.append(image.getpixel((x,y))[0])
image_list.append(row)
image_list.append([directory[1], filename])
images_list.append(image_list)
print(f"Image set {folder_count} ({folder_count}/{len(images_to_classify_dirs)}) || {count}: {count}/{len(os.listdir(directory[0]))}")
print("\n----------------------------------------------------------------\n")
print(f"Invalidated images: ({invalid_images})\n")
images_list = random.sample(images_list, len(images_list))
print("Images has successfully been shuffled!\n")
cheat_sheet = []
for index, image in enumerate(images_list):
image_type = image[len(image)-1]
if image_type[0] == "cancer":
cheat_sheet.append(0)
elif image_type[0] == "not_cancer":
cheat_sheet.append(1)
else:
print(f"[{index}] image contains invalid ticker.")
images_list.pop(index)
continue
image_list_names.append(image_type[1])
image.pop(len(image)-1)
print("cheatsheet has been created!")
# Running Images Through Models
new_folder = f"Test #{randrange(10000)}"
os.mkdir(f"test_results/{new_folder}")
print(f"\noutput folder: {new_folder}\n")
accuracies = []
undetermined_list = []
total_times = []
rights_wrongs = []
for count, (model, model_name) in enumerate(zip(models, model_names)):
print(f"Testing {model_name}...")
p_start_time = perf_counter()
predictions = model.predict(images_list, verbose=2)
prediction_time = round((perf_counter() - p_start_time) * 1000) / 1000
with open(f"test_results/{new_folder}/{model_name}.txt", "a") as f:
f.write(f"Brain Cancer Accuracy Test Report\n\nModel: {model_name}\n")
f.write(f"\nTotal Prediction Time: {round(prediction_time, 2)} second(s)\nTime-Per-Image: {round(prediction_time / len(images_list), 2)} second(s)\n\nImages: {len(images_list)}\n\n")
accuracy, undetermined, right, wrong = getModelAccuracy(predictions, cheat_sheet)
accuracies.append(accuracy)
undetermined_list.append(undetermined)
total_times.append(prediction_time)
rights_wrongs.append([right, wrong])
f.write(f"accuracy: {round(accuracy, 2)}%\n")
f.write(f"undetermined_range: {undetermined_range}\n")
f.write(f"define_rate: {round(((len(images_list) - undetermined) / len(images_list) * 100), 2)}%\n")
f.write(f"\nundetermined: {undetermined} images || right: {right} images || wrong: {wrong} images")
f.write(f"\n\nRaw Data:\n\n")
for prediction, anwser, filename in zip(predictions, cheat_sheet, image_list_names):
save = f"{filename} || Raw output: {prediction} || Actual Tag: {getAnwserTag(anwser)} || {getAccuracyTag(prediction, anwser)}\n"
f.write(save)
print(f"{model_name} Tested! [{datetime.timedelta(seconds = round(prediction_time))}] --> ({count + 1}/{len(models)})\n")
print("\n---------------------------------------------\n")
print("Building Conclusion Folder...\n")
with open(f"test_results/{new_folder}/conclusion.txt", 'a') as f:
f.write(f"Brain Cancer Accuracy Test Report Conclusion\n")
f.write(f"\nUndetermined Range: {undetermined_range}\n")
for model_name, accuracy, undetermined, prediction_time, right_wrong in zip(model_names, accuracies, undetermined_list, total_times, rights_wrongs):
f.write(f"\n\n{model_name} stats: \n\nprediction_time: {round(prediction_time, 2)} seconds \ntime_per_image: {round(prediction_time / len(images_list), 2)} second(s) \naccuracy: {round(accuracy, 2)}% \ndefine_rate: {round(((len(images_list) - undetermined) / len(images_list) * 100), 2)}% \nundetermined: {undetermined} \nright: {right_wrong[0]} \nwrong: {right_wrong[1]}\n")
print("Finished Building Conclusion File!")
print(f"\nAll data has been saved in the {new_folder} folder!")