-
Notifications
You must be signed in to change notification settings - Fork 0
/
pretraining.py
154 lines (122 loc) · 3.7 KB
/
pretraining.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
import tensorflow as tf
import keras
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import seaborn as sns
import coremltools as ct
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# load dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
# preprocessing
x_train = np.array([cv2.bitwise_not(img) for img in x_train])
x_test = np.array([cv2.bitwise_not(img) for img in x_test])
x_train, x_test = x_train.reshape(-1,28,28,1) / 255.0, x_test.reshape(-1,28,28,1) / 255.0
print(x_train.shape)
print(x_test.shape)
# initialize model (lenet-5)
model = keras.Sequential()
model.add(keras.layers.Conv2D(
filters=6,
kernel_size=(5,5),
strides=(1,1),
activation='relu',
input_shape=(28,28,1)))
model.add(keras.layers.AveragePooling2D())
model.add(keras.layers.Conv2D(
filters=16,
kernel_size=(5,5),
strides=(1,1),
activation='relu'))
model.add(keras.layers.AveragePooling2D())
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(120,activation='relu'))
model.add(keras.layers.Dense(84,activation='relu'))
model.add(keras.layers.Dense(10,activation='softmax'))
model.summary()
model.compile(
loss = keras.losses.SparseCategoricalCrossentropy(),
optimizer = 'adam',
metrics = ['accuracy']
)
# train
model.fit(
x=x_train,
y=y_train,
batch_size=64,
epochs=20,
validation_data=(x_test, y_test)
)
# plot training loss
loss = pd.DataFrame(model.history.history)
fig = loss.plot()
fig.set_title('Pretraining Loss Plot')
fig.set_xlabel('Epoch')
fig.set_ylabel('Percent')
fig = fig.get_figure()
fig.savefig('results/Pretraining_Loss_Plot.png')
plt.close()
# test
model.evaluate(
x_test,
y_test,
batch_size=128,
verbose=2)
labels = y_test
predictions = model.predict(x_test).argmax(axis=-1)
print("labels before: ",labels)
print("predictions before: ",predictions)
cm = tf.math.confusion_matrix(labels=y_test,predictions=predictions)
sns.heatmap(cm,annot=True)
plt.title("Pretraining Confusion Matrix")
plt.ylabel("True Label")
plt.xlabel("Predicted Label")
plt.savefig("results/pretraining_cm.png")
# save model
model.save('model_pretrained.h5')
# coremodel = ct.convert(
# 'model_pretrained.h5',
# input_names=['image'],
# output_names=['output'],
# image_input_names='image'
# )
# class LeNet5(tf.keras.Model):
# def __init__(self):
# super().__init__()
# self.c1 = tf.keras.layers.Conv2D(
# filters=6,
# kernel_size=(5,5),
# strides=(1,1),
# activation='relu',
# input_shape=(28,28,1))
# self.s2 = tf.keras.layers.AveragePooling2D()
# self.c3 = tf.keras.layers.Conv2D(
# filters=16,
# kernel_size=(5,5),
# strides=(1,1),
# activation='relu')
# self.s4 = tf.keras.layers.AveragePooling2D()
# self.flatten = tf.keras.layers.Flatten()
# self.fc5 = tf.keras.layers.Dense(120,activation='relu')
# self.fc6 = tf.keras.layers.Dense(84,activation='relu')
# self.fc7 = tf.keras.layers.Dense(10,activation='softmax')
# def call(self,inputs):
# x = self.c1(inputs)
# x = self.s2(x)
# x = self.c3(x)
# x = self.s4(x)
# x = self.flatten(x)
# x = self.fc5(x)
# x = self.fc6(x)
# x = self.fc7(x)
# return x
# def summary(self):
# x = tf.keras.Input(shape=(28, 28,1))
# model = tf.keras.Model(inputs=[x], outputs=self.call(x))
# return model.summary()