-
Notifications
You must be signed in to change notification settings - Fork 32
/
train.py
executable file
·194 lines (168 loc) · 8.43 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
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Author: Lukasz Janyst <[email protected]>
# Date: 14.06.2017
#-------------------------------------------------------------------------------
import argparse
import math
import sys
import os
import tensorflow as tf
import numpy as np
from fcnvgg import FCNVGG
from utils import *
from tqdm import tqdm
#-------------------------------------------------------------------------------
# Parse the commandline
#-------------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='Train the FCN')
parser.add_argument('--name', default='test',
help='project name')
parser.add_argument('--data-source', default='kitti',
help='data source')
parser.add_argument('--data-dir', default='data',
help='data directory')
parser.add_argument('--vgg-dir', default='vgg_graph',
help='directory for the VGG-16 model')
parser.add_argument('--epochs', type=int, default=10,
help='number of training epochs')
parser.add_argument('--batch-size', type=int, default=20,
help='batch size')
parser.add_argument('--tensorboard-dir', default="tb",
help='name of the tensorboard data directory')
parser.add_argument('--checkpoint-interval', type=int, default=50,
help='checkpoint interval')
args = parser.parse_args()
print('[i] Project name: ', args.name)
print('[i] Data source: ', args.data_source)
print('[i] Data directory: ', args.data_dir)
print('[i] VGG directory: ', args.vgg_dir)
print('[i] # epochs: ', args.epochs)
print('[i] Batch size: ', args.batch_size)
print('[i] Tensorboard directory:', args.tensorboard_dir)
print('[i] Checkpoint interval: ', args.checkpoint_interval)
try:
print('[i] Creating directory {}...'.format(args.name))
os.makedirs(args.name)
except (IOError) as e:
print('[!]', str(e))
sys.exit(1)
#-------------------------------------------------------------------------------
# Configure the data source
#-------------------------------------------------------------------------------
print('[i] Configuring data source...')
try:
source = load_data_source(args.data_source)
source.load_data(args.data_dir, 0.1)
print('[i] # training samples: ', source.num_training)
print('[i] # validation samples: ', source.num_validation)
print('[i] # classes: ', source.num_classes)
print('[i] Image size: ', source.image_size)
train_generator = source.train_generator
valid_generator = source.valid_generator
label_colors = source.label_colors
except (ImportError, AttributeError, RuntimeError) as e:
print('[!] Unable to load data source:', str(e))
sys.exit(1)
#-------------------------------------------------------------------------------
# Create the network
#-------------------------------------------------------------------------------
with tf.Session() as sess:
print('[i] Creating the model...')
net = FCNVGG(sess)
net.build_from_vgg(args.vgg_dir, source.num_classes, progress_hook='tqdm')
labels = tf.placeholder(tf.float32,
shape=[None, None, None, source.num_classes])
optimizer, loss = net.get_optimizer(labels)
summary_writer = tf.summary.FileWriter(args.tensorboard_dir, sess.graph)
saver = tf.train.Saver(max_to_keep=10)
label_mapper = tf.argmax(labels, axis=3)
n_train_batches = int(math.ceil(source.num_training/args.batch_size))
initialize_uninitialized_variables(sess)
print('[i] Training...')
#---------------------------------------------------------------------------
# Summaries
#---------------------------------------------------------------------------
validation_loss = tf.placeholder(tf.float32)
validation_loss_summary_op = tf.summary.scalar('validation_loss',
validation_loss)
training_loss = tf.placeholder(tf.float32)
training_loss_summary_op = tf.summary.scalar('training_loss',
training_loss)
validation_img = tf.placeholder(tf.float32, shape=[None, None, None, 3])
validation_img_gt = tf.placeholder(tf.float32, shape=[None, None, None, 3])
validation_img_summary_op = tf.summary.image('validation_img',
validation_img)
validation_img_gt_summary_op = tf.summary.image('validation_img_gt',
validation_img_gt)
validation_img_summary_ops = [validation_img_summary_op,
validation_img_gt_summary_op]
for e in range(args.epochs):
#-----------------------------------------------------------------------
# Train
#-----------------------------------------------------------------------
generator = train_generator(args.batch_size)
description = '[i] Epoch {:>2}/{}'.format(e+1, args.epochs)
training_loss_total = 0
for x, y in tqdm(generator, total=n_train_batches,
desc=description, unit='batches'):
feed = {net.image_input: x,
labels: y,
net.keep_prob: 0.5}
loss_batch, _ = sess.run([loss, optimizer], feed_dict=feed)
training_loss_total += loss_batch * x.shape[0]
training_loss_total /= source.num_training
#-----------------------------------------------------------------------
# Validate
#-----------------------------------------------------------------------
generator = valid_generator(args.batch_size)
validation_loss_total = 0
imgs = None
img_labels = None
img_labels_gt = None
for x, y in generator:
feed = {net.image_input: x,
labels: y,
net.keep_prob: 1}
loss_batch, img_classes, y_mapped = sess.run([loss,
net.classes,
label_mapper],
feed_dict=feed)
validation_loss_total += loss_batch * x.shape[0]
if imgs is None:
imgs = x[:3, :, :, :]
img_labels = img_classes[:3, :, :]
img_labels_gt = y_mapped[:3, :, :]
validation_loss_total /= source.num_validation
#-----------------------------------------------------------------------
# Write loss summary
#-----------------------------------------------------------------------
feed = {validation_loss: validation_loss_total,
training_loss: training_loss_total}
loss_summary = sess.run([validation_loss_summary_op,
training_loss_summary_op],
feed_dict=feed)
summary_writer.add_summary(loss_summary[0], e)
summary_writer.add_summary(loss_summary[1], e)
#-----------------------------------------------------------------------
# Write image summary every 5 epochs
#-----------------------------------------------------------------------
if e % 5 == 0:
imgs_inferred = draw_labels_batch(imgs, img_labels, label_colors)
imgs_gt = draw_labels_batch(imgs, img_labels_gt, label_colors)
feed = {validation_img: imgs_inferred,
validation_img_gt: imgs_gt}
validation_img_summaries = sess.run(validation_img_summary_ops,
feed_dict=feed)
summary_writer.add_summary(validation_img_summaries[0], e)
summary_writer.add_summary(validation_img_summaries[1], e)
#-----------------------------------------------------------------------
# Save a checktpoint
#-----------------------------------------------------------------------
if (e+1) % args.checkpoint_interval == 0:
checkpoint = '{}/e{}.ckpt'.format(args.name, e+1)
saver.save(sess, checkpoint)
print('Checkpoint saved:', checkpoint)
checkpoint = '{}/final.ckpt'.format(args.name)
saver.save(sess, checkpoint)
print('Checkpoint saved:', checkpoint)