-
Notifications
You must be signed in to change notification settings - Fork 1
/
mmafighters.py
147 lines (122 loc) · 5.25 KB
/
mmafighters.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
# -*- coding: utf-8 -*-
"""MMAFighters.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FVF4Nnog-dPDO6MULw6EGEC5EuLKQk18
"""
import keras
from keras import backend as K
from keras.layers.core import Dense, Activation
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.models import Model
from keras.applications import imagenet_utils
import numpy as np
from IPython.display import Image
#Initialise the global variables dictionary
gV = {}
#This is a global variable that corresponds to our classes
gV['predictionMap'] = ['Connor McGregor',
'Jon Jones',
'Khabib Nurmagomedov',
'Daniel Cormier',
'Robert Whittaker']
#This prepares our images for prediction or training
def prepare_image(file):
#Set the image path as blank, essentially no path
img_path = ''
#Load the image from the filename and shrink to be 224x224 pixels
img = image.load_img(img_path + file, target_size=(224, 224))
#Convert the image to an array, this has the shape of (224,224,3)
img_array = image.img_to_array(img)
#Print the shape of the array
#Add another dimension to the array
img_array_expanded_dims = np.expand_dims(img_array, axis=0)
#Check the new shape of the array
#Call the pre-process method from the 'mobile' model, no idea what this does
#Actually looks like this does the following
#1) Divide by 255
#2) Subtract 0,5
#3) Multiply by 2
#I imagine it does this on every element in the array
'''
def preprocess_input(x):
x /= 255.
x -= 0.5
x *= 2.
return x
'''
return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims)
#This takes our predictions and turns them into a readable label
def decodePredictions(predictions, predictionMap):
#Initialise dictionary to hold our labels and predictions
decoded = {}
#Iterate over our labels and set the probability
for i in range(len(predictionMap)):
decoded[predictionMap[i]] = predictions[0][i]
return decoded
mobileMMA = keras.applications.mobilenet.MobileNet(weights=None, classes=5)
#Set the image that we want to predict
gV['imageFiles'] = {'Khabib Nurmagomedov': ['khabib1.jpg','khabib2.jpg','khabib3.jpg','khabib4.jpg','khabib5.jpg'],
'Jon Jones': ['jon1.jpg','jon2.jpeg','jon3.jpeg','jon4.jpg','jon5.jpg'],
'Daniel Cormier': ['daniel1.jpg','daniel2.jpg','daniel3.jpg','daniel4.jpg','daniel5.jpg'],
'Robert Whittaker': ['robert1.jpg','robert2.jpg','robert3.JPG','robert4.jpg','robert5.jpg'],
'Connor McGregor': ['connor1.jpg','connor2.jpg','connor3.jpg','connor4.jpg','connor5.jpg']
}
#This just previews the image
Image(filename=gV['imageFiles']['Khabib Nurmagomedov'][0])
"""# New Section"""
preprocessed_image = prepare_image(gV['imageFiles']['Khabib Nurmagomedov'][0])
#Make a prediction
predictions = mobileMMA.predict(preprocessed_image)
readablePredictions = decodePredictions(predictions, gV['predictionMap'])
print(readablePredictions)
mobileMMA.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
#Initialise our training images with a placeholder
trainingImages = preprocessed_image
validImages = preprocessed_image
#Initialise our labels
trainingLabels = []
validLabels = []
#Iterate over our images and create our training batch and target labels
for key in gV['imageFiles']:
numberImages = len(gV['imageFiles'][key])
for i in range(numberImages):
preprocessedImage = prepare_image(gV['imageFiles'][key][i])
if (i+1 == numberImages):
validImages = np.concatenate([validImages, preprocessedImage],axis=0)
validLabels.append(gV['predictionMap'].index(key))
else:
trainingImages = np.concatenate([trainingImages, preprocessedImage],axis=0)
trainingLabels.append(gV['predictionMap'].index(key))
#Remove our placeholder
trainingImages = trainingImages[1:,:]
validImages = validImages[1:,:]
print(trainingImages.shape, validImages.shape)
#Need a vector with labels 0 through 5. Can then use the one_hot_labels below
trainingLabels = np.asarray(trainingLabels)
validLabels = np.asarray(validLabels)
#Encode our labels
one_hot_labels_train = keras.utils.to_categorical(trainingLabels, num_classes=5)
one_hot_labels_valid = keras.utils.to_categorical(validLabels, num_classes=5)
datagen = ImageDataGenerator(
featurewise_center=True,
featurewise_std_normalization=True,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True)
datagen.fit(trainingImages)
mobileMMA.fit_generator(datagen.flow(trainingImages, one_hot_labels_train, batch_size=5),
steps_per_epoch=len(trainingImages) / 5, epochs=10)
#Make a prediction
preprocessed_image = prepare_image(gV['imageFiles']['Connor McGregor'][1])
predictions = mobileMMA.predict(preprocessed_image)
readablePredictions = decodePredictions(predictions, gV['predictionMap'])
print(readablePredictions)
score = mobileMMA.evaluate(validImages, one_hot_labels_valid, batch_size=5)
print(score)