-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
254 lines (208 loc) · 8.39 KB
/
train.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
"""Import Libraries"""
import tensorflow_datasets as tfds
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import random
from keras import backend as K
import model
import datetime
import losses
# the runtime initialization will not allocate all memory on the device
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)
# 80% train 15% validation
DATA_TRAIN = tfds.load("humanoidSoccerDataset", split='train[:80%]', shuffle_files=True)
DATA_VALID = tfds.load("humanoidSoccerDataset", split='train[80%:]', shuffle_files=True)
# define some constants
TRAIN_SIZE = sum(1 for _ in DATA_TRAIN)
VALID_SIZE = sum(1 for _ in DATA_VALID)
IMAGE_WIDTH = 320
IMAGE_HEIGHT = 240
BATCH_SIZE = 12
PALETTE = {
"Ball" :np.array([[180., 120., 31.]],dtype=np.float32),
"Field" :np.array([[25. , 176., 106.]],dtype=np.float32),
"Robots" :np.array([[235., 62., 156.]],dtype=np.float32),
"Line" :np.array([[255., 255., 255.]],dtype=np.float32),
"Background" :np.array([[232., 144., 69.]],dtype=np.float32),
"Goal" :np.array([[28. , 26., 227.]],dtype=np.float32),
}
CLASSES_NUMBER = len(PALETTE.keys())
def _one_hot_encode(img):
"""Converts mask to a one-hot encoding specified by the semantic map."""
semantic_map = []
for category in PALETTE :
class_map = tf.zeros((IMAGE_HEIGHT,IMAGE_WIDTH), dtype=tf.dtypes.bool, name=None)
for color in PALETTE[category]:
p_map = tf.reduce_all(tf.equal(img, color), axis=-1)
class_map = tf.math.logical_or(p_map,class_map)
semantic_map.append(class_map)
semantic_map = tf.stack(semantic_map, axis=-1)
semantic_map = tf.cast(semantic_map, tf.float32)
return semantic_map
def random_flip_example(image, label):
seed = random.random()*10
return tf.image.random_flip_left_right(image ,seed=seed),tf.image.random_flip_left_right(label ,seed=seed)
def augmentor(data_set):
ds = data_set.map(
lambda data: (data["image"],data["label"])
).map(
lambda image, label: (tf.image.random_hue(image, 0.08), label)
).map(
lambda image, label: (tf.image.random_saturation(image, 1, 3), label)
).map(
lambda image, label: (random_flip_example(image, label))
).map(
lambda image, label: (tf.image.random_brightness(image, 0.3), label)
).map(
lambda image, label: (tf.cast(image,tf.float32) ,_one_hot_encode(label))
).batch(
BATCH_SIZE
).repeat()
return ds
# 2. Show some dataset
# train_to_show = DATA_TRAIN.map(
# lambda data: (tf.cast(data["image"], tf.float32)/255., data['label'])
# ).batch(
# 64
# )
# valid_to_show = DATA_VALID.map(
# lambda data: (tf.cast(data["image"], tf.float32)/255., data['label'])
# ).batch(
# 64
# )
# train_to_calculate_weights = iter(train_to_show)
# t_iterator = iter(train_to_show)
# v_iterator = iter(valid_to_show)
# t_next_val = t_iterator.get_next()
# v_next_val = v_iterator.get_next()
# t_buf = t_next_val
# v_buf = v_next_val
# for ii in range(2):
# # print(t_buf[0][ii])
# plt.subplot(2, 4, ii*2+1)
# plt.imshow(t_buf[0][ii])
# plt.axis("off")
# plt.title("Train Image")
# plt.subplot(2, 4, ii*2+2)
# plt.imshow(t_buf[1][ii])
# plt.axis("off")
# plt.title("Train Label")
# for ii in range(2, 4):
# plt.subplot(2, 4, ii*2+1)
# plt.imshow(v_buf[0][ii])
# plt.axis("off")
# plt.title("Valid Image")
# plt.subplot(2, 4, ii*2+2)
# plt.imshow(v_buf[1][ii])
# plt.axis("off")
# plt.title("Valid Label")
# plt.show()
# 3. One-hot encoding
train_data = augmentor(DATA_TRAIN)
valid_data = augmentor(DATA_VALID)
print("asdfasdasdf")
plot_dataset = False
if plot_dataset:
def display_sample(display_list):
"""Show side-by-side an input image,
the ground truth and the prediction.
"""
# print(tf.math.reduce_max (image),tf.math.reduce_min (image))
plt.figure(figsize=(18, 18))
title = ['Input Image', 'True Mask', 'Predicted Mask']
for i in range(len(display_list)):
plt.subplot(1, len(display_list), i+1)
plt.title(title[i])
plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i]))
plt.axis('off')
plt.show()
for image, mask in train_data.take(100):
display_sample([image[0], mask[0]])
# 3. Data normalization and Augmentation
# 4. Show some dataset after augmentation /////////////////////
# t_iterator = iter(train_data)
# v_iterator = iter(valid_data)
# t_next_val = t_iterator.get_next()
# v_next_val = v_iterator.get_next()
# plt.figure(figsize = (12,18), dpi = 300)
# plt.subplot(2,7,1)
# plt.imshow(t_next_val[0][0]/255.)
# plt.axis("off")
# plt.title("Train Aug")
# for ii in range(6):
# plt.subplot(2,7,ii+2)
# plt.imshow(t_next_val[1][0][:,:,ii], cmap='gray')
# plt.subplot(2,7,8)
# plt.imshow(v_next_val[0][0]/255.)
# plt.axis("off")
# plt.title("Valid Aug")
# for ii in range(6):
# plt.subplot(2,7,ii+9)
# plt.imshow(v_next_val[1][0][:,:,ii], cmap='gray')
# plt.show()
# ////////////////////////////////////////////////////////////
model = model.unet_model((IMAGE_HEIGHT, IMAGE_WIDTH, 3), CLASSES_NUMBER)
total_iou = losses.total_mean_iou(CLASSES_NUMBER)
ball_iou = losses.object_mean_iou("ball_iou" )
field_iou = losses.object_mean_iou("field_iou" )
robots_iou = losses.object_mean_iou("robots_iou" )
line_iou = losses.object_mean_iou("line_iou" )
background_iou = losses.object_mean_iou("background_iou" )
goal_iou = losses.object_mean_iou("goal_iou" )
metrics =[losses.dice_coef, losses.jaccard_coef, ball_iou, field_iou, line_iou, robots_iou, background_iou, goal_iou, total_iou]
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3), loss=losses.multi_category_focal_loss1, metrics=metrics)
# 5. Defining Callbacks
# model.save_weights('/home/mrl/Desktop/model/FINAL-MODEL/Humanoid.h5')
model_name = "/home/mrl/semantic segmentation article/models/Humanoid.h5"
log_dir = "Logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience = 30)
monitor = tf.keras.callbacks.ModelCheckpoint(model_name, monitor='val_loss',\
verbose=0,save_best_only=True,\
save_weights_only=True,\
mode='min')
# Learning rate schedule
def scheduler(epoch, lr):
if epoch%20 == 0 and epoch!= 0:
lr = lr/2
return lr
lr_schedule = tf.keras.callbacks.LearningRateScheduler(scheduler,verbose = 0)
# # 6. Train the model
EPOCHS = 420
STEPS_PER_EPOCH = TRAIN_SIZE / BATCH_SIZE
VALIDATION_STEPS = 5
callbacks = [early_stop, monitor, lr_schedule, tensorboard_callback]
model_history = model.fit(train_data, epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
validation_steps=VALIDATION_STEPS,
validation_data=valid_data,
callbacks=callbacks)
#TODO
"""
model_name = "models/segmentation"
log_dir = "Logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience = 30)
monitor = tf.keras.callbacks.ModelCheckpoint(model_name, monitor='val_loss',\
verbose=0,save_best_only=True,\
save_weights_only=False,\
mode='min')
# Learning rate schedule
def scheduler(epoch, lr):
if epoch%20 == 0 and epoch!= 0:
lr = lr/2
return lr
lr_schedule = tf.keras.callbacks.LearningRateScheduler(scheduler,verbose = 0)
# 6. Train the model
EPOCHS = 420
STEPS_PER_EPOCH = TRAIN_SIZE / BATCH_SIZE
VALIDATION_STEPS = VALID_SIZE / BATCH_SIZE
callbacks = [early_stop, monitor, lr_schedule, tensorboard_callback]
model_history = model.fit(train_data, epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
validation_steps=VALIDATION_STEPS,
validation_data=valid_data,
callbacks=callbacks)
"""