FCN.py语义分割脚本代码小白级注释

当初刚开始看FCN.py脚本代码时,有部分不太明白的,就给脚本增加了一些注释,具体见下方(参考增加了网上各位同学的注释,以更全面),供各位初学者参考:

基本上(有可能)是目前网上最全的注释了

  1 from __future__ import print_function
  2 import tensorflow as tf
  3 import numpy as np
  4 
  5 import TensorflowUtils as utils
  6 import read_MITSceneParsingData as scene_parsing
  7 import datetime
  8 import BatchDatsetReader as dataset
  9 from six.moves import xrange
 10 
 11 FLAGS = tf.flags.FLAGS
 12 tf.flags.DEFINE_integer("batch_size", "2", "batch size for training")
 13 tf.flags.DEFINE_string("logs_dir", "logs/", "path to logs directory")
 14 tf.flags.DEFINE_string("data_dir", "Data_zoo/MIT_SceneParsing/", "path to dataset")
 15 tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer")
 16 tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat")
 17 tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False")
 18 tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize")
 19 
 20 # 选择模式,现有train和visualize,test在下面没有找到对应的代码
 21 # train会处理训练集,并生成模型,保存在logs中
 22 # visualize会处理valid集合,并使用logs中生成的模型,可以参考这部分代码完成自己的分割程序
 23 
 24 
 25 MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'
 26 
 27 # 迭代的最大次数
 28 MAX_ITERATION = int(1e5 + 1)
 29 # 分类的个数
 30 NUM_OF_CLASSESS = 151
 31 # 图片尺寸
 32 IMAGE_SIZE = 224
 33 
 34 # vgg_net: 根据权重构建vgg网络
 35 ## vgg 网络部分, weights 是vgg网络各层的权重集合, image是被预测的图像的向量
 36 
 37 def vgg_net(weights, image):
 38     ## fcn的前五层网络就是vgg网络
 39     layers = (
 40         'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
 41 
 42         'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
 43 
 44         'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',
 45         'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
 46 
 47         'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',
 48         'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
 49 
 50         'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',
 51         'relu5_3', 'conv5_4', 'relu5_4'
 52     )
 53 #     weights 是vgg网络各层的权重集合,存储格式mat
 54     net = {}
 55     current = image
 56     for i, name in enumerate(layers):   #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
 57         kind = name[:4]
 58         # 卷积层
 59         if kind == 'conv':
 60             kernels, bias = weights[i][0][0][0][0]
 61             # kernels的获取方式是weights[第i层][0][0][0][0][0],形状为[width, height, in_channels, out_channels],bias的获取方式是weights[0][0][0][0][0],形状为[1,out_channels]。
 62             # 对于VGG-19的卷积,全部采用了3X3的filters,所以width为3,height为3。注意,这里面的层数i,指的是最细粒度的层数,包括conv、relu、pool、fc各种操作。
 63             # 因此,i=0为卷积核,i=1为relu,i=2为卷积核,i=3为relu,i=4为pool,i=5为卷积核……,i=37为全连接层,以此类推。VGG-19的pooling采用了长宽为2X2的max-pooling。
 64             # weights[i][0][0][0][0]的输出前面是kernel矩阵,后面是bias矩阵。
 65 
 66             # matconvnet: weights are [width, height, in_channels, out_channels]
 67             # tensorflow: weights are [height, width, in_channels, out_channels]
 68             #  get_variabl创建新的tensorflow变量  (这里用的是常量初始化)
 69             kernels = utils.get_variable(np.transpose(kernels, (1, 0, 2, 3)), name=name + "_w")      
 70             bias = utils.get_variable(bias.reshape(-1), name=name + "_b")  #reshape(-1)将bias转化为一维向量
 71             current = utils.conv2d_basic(current, kernels, bias)
 72         # 激活函数    
 73         elif kind == 'relu':
 74             current = tf.nn.relu(current, name=name)
 75             # FLAGS.debug 表示是否调试,如果是调试,则输出调试信息
 76             if FLAGS.debug:
 77                 utils.add_activation_summary(current)
 78         # 池化层
 79         ## vgg 的前5层的stride都是2,也就是前5层的size依次减小1倍
 80         ## 这里处理了前4层的stride,用的是平均池化
 81         ## 第5层的pool在下文的外部处理了,用的是最大池化
 82         ## pool1 size缩小2倍
 83         ## pool2 size缩小4倍
 84         ## pool3 size缩小8倍
 85         ## pool4 size缩小16倍
 86         elif kind == 'pool':
 87             current = utils.avg_pool_2x2(current)    # 平均池化
 88         net[name] = current
 89     ## vgg每层的结果都保存在net中了
 90     return net
 91 
 92 # 定义Semantic segmentation network,使用VGG结构
 93 ## 预测流程,image是输入图像的向量,keep_prob是dropout rate(dropout rate,丢失率,一般设置为0.3-0.5 调好了就是加大模型鲁棒性,调不好就是overfitting )
 94 def inference(image, keep_prob):
 95     """
 96     # inference: 推理
 97     Semantic segmentation network definition      ## 语义分割网络
 98     :param image: input image. Should have values in range 0-255
 99     :param keep_prob:
100     :return:
101     """
102 
103     ## 获取训练好的vgg部分的model
104     print("setting up vgg initialized conv layers ...")
105     # download Model,建议提前下好,这样不会重新下载
106     # 关于model的结构,可以看
107     model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL)
108 
109     mean = model_data['normalization'][0][0][0]
110     mean_pixel = np.mean(mean, axis=(0, 1))  #求出各个通道的平均值(3通道img,(H,W,3)),axis=(0, 1)其实表示的是对第0和1维共同展成的二维平面进行求均值。
111     # layers字段,所有的权重都存在这里面
112     # 关于numpy的squeeze,可以看 https://blog.csdn.net/zenghaitao0128/article/details/78512715
113     # np.squeeze 去掉数组的维度,从数组的形状中删除单维条目,即把shape中为1的维度去掉.
114     weights = np.squeeze(model_data['layers'])
115 
116     ## 将图像的向量值都减去平均像素值,进行 normalization
117     # image - mean_pixel:每一channel的均值
118     processed_image = utils.process_image(image, mean_pixel)
119 
120     # 以inference为名的命名空间
121     with tf.variable_scope("inference"):
122         # 构建VGG网络
123         ## 计算前五层vgg网络的输出结果
124         image_net = vgg_net(weights, processed_image)
125         # 最后一层
126         conv_final_layer = image_net["conv5_3"]
127         # 最后添加一层2*2的max pool
128         ## pool1 size缩小2倍
129         ## pool2 size缩小4倍
130         ## pool3 size缩小8倍
131         ## pool4 size缩小16倍
132         ## pool5 size缩小32倍
133         pool5 = utils.max_pool_2x2(conv_final_layer)
134 
135         ## 初始化第6层的w、b
136         ## 7*7 卷积核的视野很大
137         # 再加conv6,conv7,conv8三个卷基层,都用的ReLU
138         W6 = utils.weight_variable([7, 7, 512, 4096], name="W6")
139         b6 = utils.bias_variable([4096], name="b6")
140         conv6 = utils.conv2d_basic(pool5, W6, b6)
141         relu6 = tf.nn.relu(conv6, name="relu6")
142         if FLAGS.debug:
143             utils.add_activation_summary(relu6)
144         relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)
145 
146         ## 在第6层没有进行池化,所以经过第6层后 size缩小仍为32倍   输出[7,7,4096]
147  
148         ## 初始化第7层的w、b
149         W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7")
150         b7 = utils.bias_variable([4096], name="b7")
151         conv7 = utils.conv2d_basic(relu_dropout6, W7, b7)
152         relu7 = tf.nn.relu(conv7, name="relu7")
153         if FLAGS.debug:
154             utils.add_activation_summary(relu7)
155         relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)
156         ## 在第7层没有进行池化,所以经过第7层后 size缩小仍为32倍     输出[7,7,4096]
157  
158         ## 初始化第8层的w、b
159         ## 输出维度为NUM_OF_CLASSESS
160 
161         W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSESS], name="W8")
162         b8 = utils.bias_variable([NUM_OF_CLASSESS], name="b8")
163         conv8 = utils.conv2d_basic(relu_dropout7, W8, b8)
164         # annotation_pred1 = tf.argmax(conv8, dimension=3, name="prediction1")    #输出维度为[7,7,NUM_OF_CLASSESS]
165 
166         # now to upscale to actual image size
167         # 进行deconv操作,依次获取前面卷积前的图片大小   pool4 size缩小16倍  [14,14,512]
168         ## 开始将size提升为图像原始尺寸
169         deconv_shape1 = image_net["pool4"].get_shape()
170         W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1")
171         b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1")
172         ## 对第8层的结果进行反卷积(上采样),通道数也由NUM_OF_CLASSESS变为第4层的通道数(512)
173         conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"]))    #输出维度为[14,14,512]
174         ## 对应论文原文中的"2× upsampled prediction + pool4 prediction"
175         fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1")
176 
177         deconv_shape2 = image_net["pool3"].get_shape()
178         ## 对上一层上采样的结果进行反卷积(上采样),通道数也由上一层的通道数(512)变为第3层的通道数(256)
179         W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2")
180         b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")
181         conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))     #输出维度为[28,28,256]
182         ## 对应论文原文中的"2× upsampled prediction + pool3 prediction"
183         fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")
184 
185         ## 原始图像的height、width和通道数
186         shape = tf.shape(image)
187         ## 既形成一个列表,形式为[height, width, in_channels, out_channels]
188         deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSESS])
189         W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3")
190         b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3")
191         ## 再进行一次反卷积,将上一层的结果转化为和原始图像相同size、通道数为分类数的形式数据  pool3[28,28,256],--->[224,224,NUM_OF_CLASSESS]
192         conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)
193 
194         ## 目前conv_t3的形式为size为和原始图像相同的size,通道数与分类数相同
195         ## 这句我的理解是对于每个像素位置,根据第3维度(通道数)通过argmax能计算出这个像素点属于哪个分类
196         ## 也就是对于每个像素而言,NUM_OF_CLASSESS个通道中哪个数值最大,这个像素就属于哪个分类
197         annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
198 
199     return tf.expand_dims(annotation_pred, dim=3), conv_t3
200 
201 ## 训练
202 def train(loss_val, var_list):
203     optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
204     ## 下面是参照tf api
205     ## Compute gradients of loss_val for the variables in var_list.
206     ## This is the first part of minimize().
207     ## loss: A Tensor containing the value to minimize.
208     ## var_list: Optional list of tf.Variable to update to minimize loss.
209     ##   Defaults to the list of variables collected in the graph under the key GraphKey.TRAINABLE_VARIABLES.
210     grads = optimizer.compute_gradients(loss_val, var_list=var_list)  #计算梯度
211     if FLAGS.debug:
212         # print(len(var_list))
213         for grad, var in grads:
214             utils.add_gradient_summary(grad, var)
215     ## 下面是参照tf api
216     ## Apply gradients to variables.
217     ## This is the second part of minimize(). It returns an Operation that applies gradients.
218     return optimizer.apply_gradients(grads)
219 
220 # 主函数
221 def main(argv=None):
222     # placeholder 定义输入,keep_probability隐含层节点保持工作的概率,这是个什么效果
223     ## dropout 保留率
224     #placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存
225     keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
226     # 输入图像,3是指channel
227     ## 原始图像的向量
228     image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
229     # 标注图像,只有1个channel
230     ## 原始图像对应的标注图像的向量
231     annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation")
232     # 构建训练模型
233     ## 输入原始图像向量、保留率,得到预测的标注图像和随后一层的网络输出
234     pred_annotation, logits = inference(image, keep_probability)    # inference() 推理   在深度学习中,logits就是最终的全连接层的输出
235     ## 为了方便查看图像预处理的效果,可以利用 TensorFlow 提供的 tensorboard 工具进行可视化,直接用 tf.summary.image 将图像写入 summary
236     ## tensorflow的可视化是使用summary和tensorboard合作完成的。   tf.summary相关API的功能就是,将定期将部分指定tensor的值保存到本地,在通过tensorboard显示。
237     tf.summary.image("input_image", image, max_outputs=2)
238     tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2)
239     tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2)
240     # 损失函数
241     ## 计算预测标注图像和真实标注图像的交叉熵    在深度学习中,交叉熵是指两个概率分布之间的距离,交叉熵越小,两个概率分布越接近
242     #像素点上求交叉熵的和, 像素间求上一步的平均数
243     # squeeze_dims=[3] 删除维度3,即通道维度
244     loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
245                                                                           labels=tf.squeeze(annotation, squeeze_dims=[3]),
246                                                                           name="entropy")))
247     loss_summary = tf.summary.scalar("entropy", loss)
248     # 优化器
249     ## 返回需要训练的变量列表
250     trainable_var = tf.trainable_variables()
251     if FLAGS.debug:
252         for var in trainable_var:
253             utils.add_to_regularization_and_summary(var)
254     ## 定义损失
255     train_op = train(loss, trainable_var)
256 
257     print("Setting up summary op...")
258     ## 定义合并变量的操作,一次性生成所有summary数据
259     summary_op = tf.summary.merge_all()
260     # tf.summary.merge_all: 将之前定义的所有summary op整合到一起
261 
262     # 会下载Train和Valid数据
263     print("Setting up image reader...")
264     ## 读取训练数据集、验证数据集
265     train_records, valid_records = scene_parsing.read_dataset(FLAGS.data_dir)
266     print(len(train_records))
267     print(len(valid_records))
268 
269     print("Setting up dataset reader")
270     ## 将训练数据集、验证数据集的格式转换为网络需要的格式
271     image_options = {'resize': True, 'resize_size': IMAGE_SIZE}
272     if FLAGS.mode == 'train':
273         train_dataset_reader = dataset.BatchDatset(train_records, image_options)
274     validation_dataset_reader = dataset.BatchDatset(valid_records, image_options)
275 
276     sess = tf.Session()
277 
278     print("Setting up Saver...")
279     saver = tf.train.Saver()
280 
281     # create two summary writers to show training loss and validation loss in the same graph
282     # need to create two folders 'train' and 'validation' inside FLAGS.logs_dir
283     #FileWriter: 创建一个file writer用来向硬盘写summary数据
284     train_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph)
285     validation_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/validation')
286 
287     sess.run(tf.global_variables_initializer())
288     ## 加载之前的checkpoint
289     ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)
290     if ckpt and ckpt.model_checkpoint_path:
291         saver.restore(sess, ckpt.model_checkpoint_path)
292         print("Model restored...")
293 
294     # 如果是train模式
295     # 迭代MAX_ITERATION次
296     # 读取下一批次图像与标注进行训练
297     # 每10轮输出一下train_loss,500轮输出一下验证集的loss
298     if FLAGS.mode == "train":
299         for itr in xrange(MAX_ITERATION):
300             ## 读取训练集的一个batch
301             train_images, train_annotations = train_dataset_reader.next_batch(FLAGS.batch_size)
302             feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85}
303 
304             ## 执行计算损失操作,让网络跑起来
305             sess.run(train_op, feed_dict=feed_dict)
306 
307             if itr % 10 == 0:
308                 train_loss, summary_str = sess.run([loss, loss_summary], feed_dict=feed_dict)
309                 print("Step: %d, Train_loss:%g" % (itr, train_loss))
310                 train_writer.add_summary(summary_str, itr)
311 
312             if itr % 500 == 0:
313                 valid_images, valid_annotations = validation_dataset_reader.next_batch(FLAGS.batch_size)
314                 valid_loss, summary_sva = sess.run([loss, loss_summary], feed_dict={image: valid_images, annotation: valid_annotations,
315                                                        keep_probability: 1.0})
316                 print("%s ---> Validation_loss: %g" % (datetime.datetime.now(), valid_loss))
317 
318                 # add validation loss to TensorBoard
319                 validation_writer.add_summary(summary_sva, itr)
320                 saver.save(sess, FLAGS.logs_dir + "model.ckpt", itr)
321 
322     elif FLAGS.mode == "visualize":
323         valid_images, valid_annotations = validation_dataset_reader.get_random_batch(FLAGS.batch_size)
324         pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,
325                                                     keep_probability: 1.0})
326         valid_annotations = np.squeeze(valid_annotations, axis=3)
327         pred = np.squeeze(pred, axis=3)
328 
329         for itr in range(FLAGS.batch_size):
330             utils.save_image(valid_images[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5+itr))
331             utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5+itr))
332             utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="pred_" + str(5+itr))
333             print("Saved image: %d" % itr)
334 
335 
336 if __name__ == "__main__":
337     tf.app.run()

 

posted @ 2022-03-21 14:46  yk要努力  阅读(132)  评论(0编辑  收藏  举报