forked from udacity/CarND-Semantic-Segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·180 lines (150 loc) · 9.57 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
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
def load_vgg(sess, vgg_path):
"""
Load Pretrained VGG Model into TensorFlow.
:param sess: TensorFlow Session
:param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb"
:return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)
"""
# TODO: Implement function
# Use tf.saved_model.loader.load to load the model and weights
vgg_tag = 'vgg16'
vgg_input_tensor_name = 'image_input:0'
vgg_keep_prob_tensor_name = 'keep_prob:0'
vgg_layer3_out_tensor_name = 'layer3_out:0'
vgg_layer4_out_tensor_name = 'layer4_out:0'
vgg_layer7_out_tensor_name = 'layer7_out:0'
tf.saved_model.loader.load(sess,[vgg_tag],vgg_path)
graph = tf.get_default_graph() # get the default graph
w1 = graph.get_tensor_by_name(vgg_input_tensor_name)
keep = graph.get_tensor_by_name(vgg_keep_prob_tensor_name)
layer3 = graph.get_tensor_by_name(vgg_layer3_out_tensor_name)
layer4 = graph.get_tensor_by_name(vgg_layer4_out_tensor_name)
layer7 = graph.get_tensor_by_name(vgg_layer7_out_tensor_name)
return w1,keep, layer3, layer4,layer7
tests.test_load_vgg(load_vgg, tf)
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):
"""
Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.
:param vgg_layer3_out: TF Tensor for VGG Layer 3 output
:param vgg_layer4_out: TF Tensor for VGG Layer 4 output
:param vgg_layer7_out: TF Tensor for VGG Layer 7 output
:param num_classes: Number of classes to classify
:return: The Tensor for the last layer of output
"""
# TODO: Implement function
l7_conv_1x1 = tf.layers.conv2d(vgg_layer7_out, num_classes, 1, padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001)) # reduce the number of filters from 4096 down to num_classes
l7_output = tf.layers.conv2d_transpose(l7_conv_1x1,num_classes, 4,2,padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001)) # increase the height and width dimensions of the input tensor
l4_scaled = tf.multiply(vgg_layer4_out, 0.01) # the l4 layer on the encoder is scaled so we have to scale it back
l4_conv_1x1 = tf.layers.conv2d(l4_scaled, num_classes, 1, padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))
l4_skip = tf.add(l7_output, l4_conv_1x1) # add skip layer
l4_output = tf.layers.conv2d_transpose(l4_skip,num_classes, 4,2,padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))
l3_scaled = tf.multiply(vgg_layer3_out, 0.0001) # the l3 layer on the encoder is scaled so we have to scale it back
l3_conv_1x1 = tf.layers.conv2d(l3_scaled, num_classes, 1, padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))
l3_skip = tf.add(l3_conv_1x1, l4_output) # add skip layer
output = tf.layers.conv2d_transpose(l3_skip,num_classes, 16,8 ,padding='same', kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))
return output
tests.test_layers(layers)
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholder for the learning rate
:param num_classes: Number of classes to classify
:return: Tuple of (logits, train_op, cross_entropy_loss)
"""
# TODO: Implement function
logits = tf.reshape(nn_last_layer, (-1,num_classes))
##### correct_label = tf.reshape(correct_label, (-1,num_classes))
cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = correct_label)) # define the loss function
regularization_loss = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # get the regularization losses
total_loss = cross_entropy_loss + sum(regularization_loss) # calculate the total loss
adam_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) # define the optimizer
train_op = adam_optimizer.minimize(cross_entropy_loss) # Define train operation
return logits, train_op, total_loss
tests.test_optimize(optimize)
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,
correct_label, keep_prob, learning_rate):
"""
Train neural network and print out the loss during training.
:param sess: TF Session
:param epochs: Number of epochs
:param batch_size: Batch size
:param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size)
:param train_op: TF Operation to train the neural network
:param cross_entropy_loss: TF Tensor for the amount of loss
:param input_image: TF Placeholder for input images
:param correct_label: TF Placeholder for label images
:param keep_prob: TF Placeholder for dropout keep probability
:param learning_rate: TF Placeholder for learning rate
"""
# TODO: Implement function
print("\ntrain_nn started\n\n")
sess.run(tf.global_variables_initializer())
for epoch in range(epochs):
print ("Epoch: ", epoch, "\n")
for image, label in get_batches_fn(batch_size):
_, loss = sess.run([train_op, cross_entropy_loss], feed_dict={
input_image: image,
correct_label: label,
keep_prob: 0.5,
learning_rate: 0.0001 })
print("loss: ",loss,"\n")
if loss <0.1: # early exit if the model is trained good engough, it saves time and it prevents overfitting
print ("The loss is good enough, exit training.")
return
tests.test_train_nn(train_nn)
def run():
create_video = True # requires imageio package. It creates a video from the processed images
num_classes = 3
# I tried to implement a version with three classes but it did not work.
# The model could not make a distinction between the current road and other roads on the images.
# I used green color for the current road and blue color for the other roads.
# The other road was colored but there were mixed color pixels on the edges.
# I included the helper_3classes.py file. It includes the code with the modifications I made to test three classes detection.
image_shape = (160, 576) # KITTI dataset uses 160x576 images
data_dir = './data'
runs_dir = './runs'
epochs = 30
batch_size = 20 # It is tested on a GPU with 11GB RAM. Reduce this value if you get an error.
tests.test_for_kitti_dataset(data_dir)
# Download pretrained vgg model
helper.maybe_download_pretrained_vgg(data_dir)
# OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset.
# You'll need a GPU with at least 10 teraFLOPS to train on.
# https://www.cityscapes-dataset.com/
with tf.Session() as sess:
# Path to vgg model
vgg_path = os.path.join(data_dir, 'vgg')
# Create function to get batches
get_batches_fn = helper.gen_batch_function(os.path.join(data_dir, 'data_road/training'), image_shape)
# OPTIONAL: Augment Images for better results
# https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network
# TODO: Build NN using load_vgg, layers, and optimize function
input_image, keep_prob, layer3_out, layer4_out, layer7_out = load_vgg(sess, vgg_path) # load the saved vgg model and create the layers of the NN
layer_output = layers(layer3_out,layer4_out, layer7_out, num_classes) # create the output layer
correct_label = tf.placeholder(tf.int32, [None, None, None, num_classes])
learning_rate = tf.placeholder(tf.float32)
logits, train_op, cross_entropy_loss = optimize(layer_output,correct_label, learning_rate, num_classes)
# TODO: Train NN using the train_nn function
train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,correct_label, keep_prob, learning_rate) # train the NN
# TODO: Save inference data using helper.save_inference_samples
helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, input_image, create_video )
# OPTIONAL: Apply the trained model to a video
if __name__ == '__main__':
run()