-
Notifications
You must be signed in to change notification settings - Fork 7
/
encoderTrain.py
172 lines (133 loc) · 5.84 KB
/
encoderTrain.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
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import matplotlib.pyplot as plt
from InverseFaceNetEncoder import InverseFaceNetEncoder
from LoadDataset import LoadDataset
from FaceNet3D import FaceNet3D as Helpers
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# TF_FORCE_GPU_ALLOW_GROWTH = False
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
tf.keras.backend.set_session(sess)
print("GPU Available:", tf.test.is_gpu_available())
class EncoderTrain(Helpers):
AUTOTUNE = tf.data.experimental.AUTOTUNE
def __init__(self):
"""
Class initializer
"""
super().__init__()
self.history_list = list()
self.inverseNet = InverseFaceNetEncoder()
def training_phase_1(self):
"""
Start training with ImageNet weights on the SyntheticDataset
"""
# Build and compile model:
self.inverseNet.compile()
model = self.inverseNet.model
keras_ds = LoadDataset().load_dataset_batches()
keras_ds = keras_ds.shuffle(self.SHUFFLE_BUFFER_SIZE).repeat().batch(
self.BATCH_SIZE).prefetch(None)
steps_per_epoch = tf.math.ceil(self.SHUFFLE_BUFFER_SIZE / self.BATCH_SIZE).numpy()
print("Training with %d steps per epoch" % steps_per_epoch)
history_1 = model.fit(keras_ds, epochs=2000, steps_per_epoch=steps_per_epoch,
callbacks=[self.cp_callback])
self.history_list.append(history_1)
def training_phase_12(self):
"""
Continue training from latest checkpoint
"""
# load latest checkpoint and continue training
latest = tf.train.latest_checkpoint(self.checkpoint_dir)
print("\ncheckpoint: ", latest)
# Build and compile model:
model = self.inverseNet.model
model.load_weights(latest)
self.inverseNet.compile()
model = self.inverseNet.model
keras_ds = LoadDataset().load_dataset_batches()
keras_ds = keras_ds.shuffle(self.SHUFFLE_BUFFER_SIZE).repeat().batch(
self.BATCH_SIZE).prefetch(buffer_size=self.AUTOTUNE)
steps_per_epoch = tf.math.ceil(self.SHUFFLE_BUFFER_SIZE / self.BATCH_SIZE).numpy()
print("Training with %d steps per epoch" % steps_per_epoch)
history_1 = model.fit(keras_ds, epochs=2000, steps_per_epoch=steps_per_epoch,
callbacks=[self.cp_callback, self.cp_stop])
self.history_list.append(history_1)
def training_phase_2(self):
"""
Bootstrap training.
"""
latest = self.trained_models_dir + "cp-b2.ckpt"
print("\ncheckpoint: ", latest)
# Build and compile model:
model = self.inverseNet.model
model.load_weights(latest)
# Build and compile model:
self.inverseNet.compile()
model = self.inverseNet.model
keras_ds = LoadDataset().load_dataset_batches()
keras_ds = keras_ds.shuffle(self.SHUFFLE_BUFFER_SIZE).repeat().batch(
self.BATCH_SIZE).prefetch(buffer_size=self.AUTOTUNE)
steps_per_epoch = tf.math.ceil(self.SHUFFLE_BUFFER_SIZE / self.BATCH_SIZE).numpy()
print("Training with %d steps per epoch" % steps_per_epoch)
history_1 = model.fit(keras_ds, epochs=300, steps_per_epoch=steps_per_epoch,
callbacks=[self.cp_callback, self.cp_stop])
self.history_list.append(history_1)
def training_phase_21(self):
# load latest checkpoint and continue training
latest = tf.train.latest_checkpoint(self.checkpoint_dir)
# latest = self.trained_models_dir + "cp-0205.ckpt"
print("\ncheckpoint: ", latest)
# Build and compile model:
model = self.inverseNet.model
model.load_weights(latest)
# Build and compile model:
self.inverseNet.compile()
model = self.inverseNet.model
# with tf.device('/device:CPU:0'):
keras_ds = LoadDataset().load_dataset_batches()
keras_ds = keras_ds.shuffle(self.SHUFFLE_BUFFER_SIZE).repeat().batch(
self.BATCH_SIZE).prefetch(buffer_size=self.AUTOTUNE)
steps_per_epoch = tf.math.ceil(self.SHUFFLE_BUFFER_SIZE / self.BATCH_SIZE).numpy()
print("Training with %d steps per epoch" % steps_per_epoch)
# with tf.device('/device:CPU:0'):
history_1 = model.fit(keras_ds, epochs=240, steps_per_epoch=steps_per_epoch,
callbacks=[self.cp_callback, self.cp_stop])
self.history_list.append(history_1)
def plots(self):
for i in range(0, len(self.history_list)):
plt.figure()
plt.ylabel("Custom Loss, phase % d" % i)
plt.xlabel("Training Steps")
plt.plot(self.batch_stats_callback.batch_losses)
plt.savefig(self.plot_path + 'batch_stats_%d.pdf' % i)
plt.figure()
plt.title('Mean Squared Error, phase %d' % i)
plt.plot(self.history_list[i].history['mean_squared_error'])
plt.savefig(self.plot_path + 'mse%d.pdf' % i)
plt.figure()
plt.title('Mean Absolute Error, phase %d' % i)
plt.plot(self.history_list[i].history['mean_absolute_error'])
plt.savefig(self.plot_path + 'mae%d.pdf' % i)
plt.figure()
plt.title('Loss, phase %d' % i)
plt.plot(self.history_list[i].history['loss'])
plt.savefig(self.plot_path + 'loss%d.pdf' % i)
def main():
train = EncoderTrain()
print("\n")
print("Batch size: %d" % train.BATCH_SIZE)
print("\nPhase 1\nSTART")
train.training_phase_1()
print("Phase 1: COMPLETE")
# print("\n \n \nPhase 2\n START")
#
# train.training_phase_2()
#
# print("Phase 2: COMPLETE")
print("Saving plots...")
train.plots()
main()