-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
255 lines (194 loc) · 9.36 KB
/
main.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import os
import tensorflow as tf
from keras import Sequential, layers, regularizers
import keras
import numpy as np
import pandas as pd
import plotly.offline as ply
import plotly.graph_objs as graphs
import math
import random
import matplotlib.pyplot as plt
def get_dims(data_dir):
"""Get dimensions from a npy file in the given data directory data_dir."""
npy_files = [file for file in os.listdir(data_dir) if file.endswith(".npy")]
example_path = os.path.join(data_dir, npy_files[0])
npy_example = np.load(example_path)
return npy_example.shape
def load_data(ids, labels, data_dir):
"""Returns 2D image arrays and labels of given IDs."""
num_samples = len(ids)
dims = get_dims(data_dir)
X = np.empty((num_samples, dims[0], dims[1], dims[2])) # Softcode dimensions
y = np.empty(num_samples, dtype=int)
# Fill data to X and y
for i, ID in enumerate(ids):
sample_path = os.path.join(data_dir, ID + '.npy')
X[i, ] = np.load(sample_path).astype("float16")
y[i] = labels[ID]
return X, keras.utils.to_categorical(y)
def split_data(ids, train_ratio=0.8, validation_ratio=0.1, test_ratio=0.1):
"""Split list of sample IDs randomly with a given ratio for the training, validation and test set."""
# Check validity of ratio arguments
if train_ratio + validation_ratio + test_ratio != 1.0:
raise Exception("Error: train_ratio, validation_ratio and test_ratio must add up to 1.0")
# Calculate number of samples in each set
num_samples = len(ids)
val_data_size = math.floor(num_samples * validation_ratio)
test_data_size = math.floor(num_samples * test_ratio)
train_data_size = num_samples - (val_data_size + test_data_size)
# Randomize sample IDs
random.seed(0)
random.shuffle(ids)
# Split data into training, validation and test set
train_ids = ids[:train_data_size]
val_ids = ids[train_data_size:train_data_size + val_data_size]
test_ids = ids[train_data_size + val_data_size:]
return {"train": train_ids, "validation": val_ids, "test": test_ids}
def plot_incorrects(model, test_images, test_labels, num_to_show=3):
"""Plot a number of incorrectly predicted images. Go to next image using Enter-key."""
num_shown = 0
for sample, label in zip(test_images, test_labels):
if num_shown >= num_to_show:
break
prediction = predict(np.array([sample]), model, show=False)
incorrects = prediction != [np.argmax(label)]
if incorrects is True:
print("True: {}\tPredicted: {}".format([np.argmax(label)], prediction))
plt.imshow(sample[:, :, 0])
plt.show()
_ = input() # Hit enter to go to next image
num_shown += 1
def plot_train_val_acc(accs, show=True):
"""Plot training vs. testing accuracy over all epochs."""
x = list(accs.keys())
y_train = [i[0] for i in accs.values()]
y_test = [i[1] for i in accs.values()]
trace_train = graphs.Scatter(x=x, y=y_train, name="Training", mode="lines+markers",
line=dict(width=4),
marker=dict(symbol="circle",
size=10))
trace_test = graphs.Scatter(x=x, y=y_test, name="Validation", mode="lines+markers",
line=dict(width=4),
marker=dict(symbol="circle",
size=10))
layout = graphs.Layout(title="Training vs. Validation accuracy",
xaxis={"title": "Epoch"},
yaxis={"title": "Accuracy"})
fig = graphs.Figure(data=[trace_train, trace_test], layout=layout)
ply.plot(fig, image_filename="plotly_train_val_acc.html", auto_open=show)
# print("Plot saved as plotly_train_val_acc.html")
def plot_train_val_loss(losses, show=True):
"""Plot training vs. testing loss over all epochs."""
x = list(losses.keys())
y_train = [i[0] for i in losses.values()]
y_test = [i[1] for i in losses.values()]
trace_train = graphs.Scatter(x=x, y=y_train, name="Training", mode="lines+markers",
line=dict(width=4),
marker=dict(symbol="circle",
size=10))
trace_test = graphs.Scatter(x=x, y=y_test, name="Validation", mode="lines+markers",
line=dict(width=4),
marker=dict(symbol="circle",
size=10))
layout = graphs.Layout(title="Training vs. Validation loss",
xaxis={"title": "Epoch"},
yaxis={"title": "Loss"})
fig = graphs.Figure(data=[trace_train, trace_test], layout=layout)
ply.plot(fig, image_filename="plotly_train_val_loss.html", auto_open=show)
# print("Plot saved as plotly_train_val_loss.html")
def predict(samples, model, show=True):
"""Return class predicted by model for the given samples."""
predictions = model.predict(samples)
if show:
print("-------")
for prediction in predictions:
print(np.argmax(prediction))
return [np.argmax(prediction) for prediction in predictions]
def create_2DCNN_model(input_shape):
"""Build architecture of the model."""
model = Sequential()
model.add(layers.Conv2D(32, (3, 3), input_shape=input_shape,
activation="relu", padding="same"))
model.add(layers.Conv2D(64, (3, 3), activation="selu", padding="same"))
model.add(layers.MaxPooling2D(pool_size=(3, 3)))
model.add(layers.Conv2D(64, (3, 3), activation="selu", padding="same"))
model.add(layers.Conv2D(64, (3, 3), activation="selu", padding="same"))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation="selu", padding="same"))
model.add(layers.MaxPooling2D(pool_size=(2, 2), padding="same"))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation="selu",
kernel_regularizer=regularizers.l2(0.001)))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(32, activation="selu"))
model.add(layers.Dense(10, activation="softmax"))
# Create model
model.compile(optimizer=tf.train.AdamOptimizer(),
loss="categorical_crossentropy",
metrics=["accuracy"])
return model
def main():
# Data directory
data_dir = "data/"
# Define hyperparameters
num_epochs = 100
batch_size = 32
train_ratio = 0.7
validation_ratio = 0.15
test_ratio = 0.15
# Get dimensions of one sample
dims = get_dims(data_dir)
# Get and map labels to sample IDs
labels_df = pd.read_csv(os.path.join(data_dir, "labels.csv"), sep=";", header=0)
labels = dict(zip(labels_df.iloc[:, 0].tolist(), labels_df.iloc[:, 1].tolist()))
# Create ID-wise training / validation partitioning
partition = split_data(ids=list(labels.keys()),
train_ratio=train_ratio,
validation_ratio=validation_ratio,
test_ratio=test_ratio)
# Load data
train_images, train_labels = load_data(partition["train"], labels, data_dir)
validation_images, validation_labels = load_data(partition["validation"], labels, data_dir)
test_images, test_labels = load_data(partition["test"], labels, data_dir)
# Create/Compile CNN model
model = create_2DCNN_model(dims)
# Train model
train_summary = model.fit(x=train_images,
y=train_labels,
validation_data=(validation_images, validation_labels),
batch_size=batch_size,
epochs=num_epochs)
print(train_summary.history)
# Evaluate fitted model using test data
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=1)
print("\nTest ACC:", round(test_acc, 3))
# =============================================================================
# Optional functions
# Get epochwise performances
# train_acc = train_summary.history["acc"]
# val_acc = train_summary.history["val_acc"]
# train_loss = train_summary.history["loss"]
# val_loss = train_summary.history["val_loss"]
# Format and store performances per epoch for plotting
# accs = {epoch: [round(performance[0], 2), round(performance[1], 2)]
# for epoch, performance in enumerate(zip(train_acc, val_acc))}
# losses = {epoch: [round(performance[0], 2), round(performance[1], 2)]
# for epoch, performance in enumerate(zip(train_loss, val_loss))}
# Plot training and validation performance over epochs
# plot_train_val_acc(accs)
# plot_train_val_loss(losses)
# Plot incorrectly predicted samples
# plot_incorrects(model, test_images, test_labels, num_to_show=5)
# Prediction of query sample
# predicted = predict(np.array([test_images[0]]), model, show=True)
# print("Predicted label:", np.argmax(predicted))
# print("True label:", np.argmax(test_labels[0]))
# Plot an image
# plt.imshow(test_images[0][:, :, 0])
# plt.show()
# Print model summary including parameters and architecture
# print(model.summary())
# =============================================================================
if __name__ == "__main__":
main()