-
Notifications
You must be signed in to change notification settings - Fork 0
/
convolutional_neural_network.py
213 lines (165 loc) · 7.64 KB
/
convolutional_neural_network.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Convolutional Neural Network
Architecture: VGG-16
@author: cynthiahabonimana
"""
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.pooling import AveragePooling2D
from keras.applications import VGG16
from keras.layers.core import Dropout
from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras.layers import Input
from keras.layers import InputLayer
from keras.models import Model
from keras.models import Sequential
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.utils import np_utils
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
class ConvolutionalNeuralNetwork:
#print ("Successfully imported convolutional neural network.")
print ("VGG-16 just joined the chat")
# partition the data into training and testing splits using 75% of
# the data for training and the remaining 25% for validation set
def __init__(self, alpha_lr):
self.alpha_lr = alpha_lr
def split (self, data, labels):
"""
Splits the image data and corresponding labels into training
and validation sets.
Training sets are saved in ``trainX`` and ``trainY``
Validation sets are saved in ``validX`` and ``validY``
"""
print ("Splitting data into training and validation sets...")
(trainX, validX, trainY, validY) = train_test_split(data, labels,
test_size=0.25, stratify=labels, random_state=42)
print("Size and shape of trainX: {}".format(trainX.shape))
print("Size and shape of trainY: {}".format(trainY.shape))
print("Size and shape of validX: {}".format(validX.shape))
print("Size and shape of validY: {}\n".format(validY.shape))
return trainX, validX, trainY, validY
"""
DATA AUGMENTATION
Keep this in comments if using saving intermediate output to disk
# initialize the training data to add more images
trainAug = ImageDataGenerator(
rotation_range=30,
zoom_range=0.15,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.15,
horizontal_flip=True,
fill_mode="nearest")
# initialize the validation data augmentation object (which
# we'll be adding mean subtraction to)
valAug = ImageDataGenerator()
# define the ImageNet mean subtraction (in RGB order) and set the
# the mean subtraction value for each of the data augmentation
# objects
mean = np.array([123.68, 116.779, 103.939], dtype="float32")
trainAug.mean = mean
#valAug.mean = mean
"""
def first_loop_model (self, data, labels):
""""
Builds a VGG-16 model that runs for one epoch.
The entire image dataset is fed to the model and
the output of the VGG-16 pretrained layers is saved into
``intermediate output``.
Returns ``intermediate output``
""""
# load VGG16, ensuring the head FC layer sets are left off, while at
# the same time adjusting the size of the input image tensor to the
# network
baseModel = VGG16(weights="imagenet", include_top=False,
input_tensor=Input(shape=(128, 128, 3)))
# show a summary of the base model
print("[INFO] summary for base model...")
print(baseModel.summary())
# construct the head of the model that will be placed on top of the
# the base model
headModel = baseModel.output
headModel = AveragePooling2D(pool_size=(4, 4))(headModel)
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(128, activation="relu")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(5, activation="softmax")(headModel)
# place the headModel on top of the base model
#model_first_loop is the model that will be trained
model_first_loop = Model(inputs=baseModel.input, outputs=headModel)
# loop over all layers in the base model and we freeze them so they will
# *not* be updated during the first training process
for layer in baseModel.layers:
layer.trainable = False
# compiling our model
print("[INFO] compiling model...")
opt = Adam(lr= self.alpha_lr)
model_first_loop.compile(loss="categorical_crossentropy", optimizer=opt,
metrics=["accuracy"])
# training the head of the network for one epoch (all other layers
# are frozen)
print("[INFO] training head...")
H_first_loop_model = model_first_loop.fit(
x=data,
y=labels,
batch_size=32,
epochs=1,
)
last_layer_base_model = Model(inputs=model_first_loop.input,
outputs=model_first_loop.layers[18].output)
intermediate_output = last_layer_base_model.predict(data)
print("Size and shape of the labels dataset are: {}".format(intermediate_output.shape))
return intermediate_output
def custom_model (self, trainX, validX, trainY, validY, lb):
"""
Trains the model using the transformed data from pre-trained layers of VGG-16
Diplays information on training and validation loss perfomance
"""
print ("Building custom new model...")
customModel = Sequential()
customModel.add (AveragePooling2D(pool_size=(4, 4), input_shape= (4,4, 512)))
customModel.add (Flatten(name="flatten"))
customModel.add (Dropout(0.5))
customModel.add (Dense(64, activation="relu"))
customModel.add (Dropout(0.5))
customModel.add (Dense(5, activation="softmax"))
# compile our model
print("[INFO] compiling custom new model...")
opt = Adam(lr= self.alpha_lr)
customModel.compile(loss="categorical_crossentropy", optimizer=opt,
metrics=["accuracy"])
# early stopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=100)
print("[INFO] training custom new model...")
H_customModel = customModel.fit(
x=trainX,
y=trainY,
validation_data=(validX, validY),
callbacks=[es],
batch_size=32,
epochs=400,
)
print("[INFO] evaluating the network...")
new_predictions = customModel.predict(validX, batch_size=32)
print(classification_report(validY.argmax(axis=1),
new_predictions.argmax(axis=1), target_names=lb.classes_))
#N = 110
plt.style.use("ggplot")
plt.figure()
plt.plot(H_customModel.history["loss"], label="train_loss")
plt.plot(H_customModel.history["val_loss"], label="val_loss")
plt.plot(H_customModel.history["accuracy"], label="train_acc")
plt.plot(H_customModel.history["val_accuracy"], label="val_acc")
plt.title("Training Loss and Accuracy on Dataset using Transformed Data")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="upper right")