FCN 項目部分代碼學習


     下面代碼由搭檔注釋,保存下來用作參考。

github項目地址:https://github.com/shekkizh/FCN.tensorflow
from
__future__ import print_function import tensorflow as tf import numpy as np import TensorflowUtils as utils import read_MITSceneParsingData as scene_parsing import datetime import BatchDatsetReader as dataset #six.moves 是用來處理那些在2 和 3里面函數的位置有變化的,直接用six.moves就可以屏蔽掉這些變化 #xrange 用來處理數據類型切換 from six.moves import xrange #執行main函數之前首先進行flags的解析,也就是說TensorFlow通過設置flags來傳遞tf.app.run()所需要的參數, #我們可以直接在程序運行前初始化flags,也可以在運行程序的時候設置命令行參數來達到傳參的目的。 ##調用flags內部的DEFINE_string函數來制定解析規則 FLAGS = tf.flags.FLAGS tf.flags.DEFINE_integer("batch_size", "2", "batch size for training") tf.flags.DEFINE_string("logs_dir", "logs/", "path to logs directory") tf.flags.DEFINE_string("data_dir", "Data_zoo/MIT_SceneParsing/", "path to dataset") tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer") tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat") tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False") tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize") MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'#如果沒有找到Vgg-19的模型,將會從這個網址進行下載 MAX_ITERATION = int(2) #類別數 NUM_OF_CLASSESS = 151 #圖片尺寸 IMAGE_SIZE = 224 ##定義vgg網絡層結構## vgg 網絡部分, weights 是vgg網絡各層的權重集合, image是被預測的圖像的向量 def vgg_net(weights, image): ## fcn的前五層網絡就是vgg網絡 layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) net = {} current = image#輸入圖片 for i, name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] print('1111:',weights[i][0][0][0][0]) # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] # 由於 imagenet-vgg-verydeep-19.mat 中的參數矩陣和我們定義的長寬位置顛倒了 #原來索引號(reshape(2,2,3))是012,現在是102 kernels = utils.get_variable(np.transpose(kernels, (1, 0, 2, 3)), name=name + "_w")#(1, 0, 2, 3)是索引號 print('kernels:',kernels) bias = utils.get_variable(bias.reshape(-1), name=name + "_b")#reshape(-1)把bias參數數組合並成一行 print('bias:',bias) current = utils.conv2d_basic(current, kernels, bias) print('current:',current) elif kind == 'relu': current = tf.nn.relu(current, name=name) print('current1:',current) if FLAGS.debug: utils.add_activation_summary(current) elif kind == 'pool': ## vgg 的前5層的stride都是2,也就是前5層的size依次減小1倍 ## 這里處理了前4層的stride,用的是平均池化 ## 第5層的pool在下文的外部處理了,用的是最大池化 ## pool1 size縮小2倍 ## pool2 size縮小4倍 ## pool3 size縮小8倍 ## pool4 size縮小16倍 current = utils.avg_pool_2x2(current)#平均池化 net[name] = current print('current2:',current) return net ## vgg每層的結果都保存再net中了 ## 預測流程,image是輸入圖像的向量,keep_prob是dropout rate def inference(image, keep_prob):#語義分割網絡定義 """ Semantic segmentation network definition :param image: input image. Should have values in range 0-255 :param keep_prob:#keep_prob: 名字代表的意思, keep_prob 參數可以為 tensor,意味着,訓練時候 feed 為0.5, :return: """ ## 獲取訓練好的vgg部分的model print("setting up vgg initialized conv layers ...")#設置vgg初始化的conv層 model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL) mean = model_data['normalization'][0][0][0]#這里個人認為上述加載后的模型保存在一個類似於字典的結構里。 print('mean:',mean) #獲取圖片像素的均值 mean_pixel = np.mean(mean, axis=(0, 1)) print('mean_pixel:',mean_pixel) weights = np.squeeze(model_data['layers']) ## 將圖像的向量值都減去平均像素值,進行 normalization processed_image = utils.process_image(image, mean_pixel) with tf.variable_scope("inference"): ## 計算前5層vgg網絡的輸出結果 image_net = vgg_net(weights, processed_image) conv_final_layer = image_net["conv5_3"] ## pool1 size縮小2倍 ## pool2 size縮小4倍 ## pool3 size縮小8倍 ## pool4 size縮小16倍 ## pool5 size縮小32倍 pool5 = utils.max_pool_2x2(conv_final_layer) ## 初始化第6層的w、b ## 7*7 卷積核的視野很大 W6 = utils.weight_variable([7, 7, 512, 4096], name="W6") b6 = utils.bias_variable([4096], name="b6") conv6 = utils.conv2d_basic(pool5, W6, b6) relu6 = tf.nn.relu(conv6, name="relu6") if FLAGS.debug: utils.add_activation_summary(relu6) relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob) ## 在第6層沒有進行池化,所以經過第6層后 size縮小仍為32倍 ## 初始化第7層的w、b W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7") b7 = utils.bias_variable([4096], name="b7") conv7 = utils.conv2d_basic(relu_dropout6, W7, b7) relu7 = tf.nn.relu(conv7, name="relu7") if FLAGS.debug: utils.add_activation_summary(relu7) relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob) ## 初始化第8層的w、b ## 輸出維度為NUM_OF_CLASSESS W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSESS], name="W8") b8 = utils.bias_variable([NUM_OF_CLASSESS], name="b8") conv8 = utils.conv2d_basic(relu_dropout7, W8, b8) # annotation_pred1 = tf.argmax(conv8, dimension=3, name="prediction1") # now to upscale to actual image size ## 開始將size提升為圖像原始尺寸(反卷積) deconv_shape1 = image_net["pool4"].get_shape() W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") ## 對第8層的結果進行反卷積(上采樣),通道數也由NUM_OF_CLASSESS變為第4層的通道數 conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"])) fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1") ## 對上一層上采樣的結果進行反卷積(上采樣),通道數也由上一層的通道數變為第3層的通道數 deconv_shape2 = image_net["pool3"].get_shape() W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2") b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2") conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"])) ## 對應論文原文中的"2× upsampled prediction + pool3 prediction" fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2") ## 原始圖像的height、width和通道數 shape = tf.shape(image) deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSESS]) W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3") ## 再進行一次反卷積,將上一層的結果轉化為和原始圖像相同size、通道數為分類數的形式數據 conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8) ## 目前conv_t3的形式為size為和原始圖像相同的size,通道數與分類數相同 ## 這句我的理解是對於每個像素位置,根據3個維度(通道數即RGB的值)通過argmax能計算出這個像素點屬於哪個分類 ## 也就是對於每個像素而言,NUM_OF_CLASSESS個通道中哪個數值最大,這個像素就屬於哪個分類 annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction") return tf.expand_dims(annotation_pred, dim=3), conv_t3 ##訓練:定義訓練損失優化器及訓練的梯度下降方法以更新參數 def train(loss_val, var_list):#測試損失 optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate) grads = optimizer.compute_gradients(loss_val, var_list=var_list) if FLAGS.debug: # print(len(var_list)) for grad, var in grads: utils.add_gradient_summary(grad, var) return optimizer.apply_gradients(grads) #主函數 def main(argv=None): keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")#定義dropout的占位符 #定義原圖和標簽的占位符用來動態存儲傳入的圖片 image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")#原始圖像的形式,None為自動查看相應的樣本數 annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation")#原始圖片對應的標簽形式 ## 輸入原始圖像向量、保留率,得到預測的標簽圖像和隨后一層的網絡logits輸出 pred_annotation, logits = inference(image, keep_probability) correct_prediction = tf.equal(tf.argmax(annotation,1),pred_annotation) acc = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) ## 為了方便查看圖像預處理的效果,可以利用 TensorFlow 提供的 tensorboard 工具進行可視化,直接用 tf.summary.image 將圖像寫入 summary #可視化原圖、標簽和預測標簽 tf.summary.image("input_image", image, max_outputs=2) tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2) tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2) ## 計算預測標注圖像和真實標注圖像的交叉熵用來確定損失函數和以產生訓練過程中的損失 loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=tf.squeeze(annotation, squeeze_dims=[3]), name="entropy"))) #可視化模型訓練過程中的損失 tf.summary.scalar("entropy", loss) ## 返回需要訓練的變量列表並進行規范化 trainable_var = tf.trainable_variables() if FLAGS.debug: for var in trainable_var: utils.add_to_regularization_and_summary(var)#規范化 #調用之前定義的優化器函數然后可視化 train_op = train(loss, trainable_var) print("Setting up summary op...") ## 定義合並變量操作,一次性生成所有摘要數據 summary_op = tf.summary.merge_all() print("Setting up image reader...") ## 讀取訓練數據集、驗證數據集 #注意讀取的時候是調用scene_parsing.read_dataset函數,這個函數可以吧數據轉為列表形式的pickle文件 train_records,valid_records = scene_parsing.read_dataset(FLAGS.data_dir) print(len(train_records)) print(len(valid_records)) print("Setting up dataset reader") ## 將訓練數據集、驗證數據集的格式轉換為網絡需要的格式 image_options = {'resize': True, 'resize_size': IMAGE_SIZE} #從文件夾images 和annotations獲取數據 if FLAGS.mode == 'train': #注意train和test分開執行train指令時順便也把測試的給執行了后面還有個預測可視化。 train_dataset_reader = dataset.BatchDatset(train_records, image_options) validation_dataset_reader = dataset.BatchDatset(valid_records, image_options) sess = tf.Session() print("Setting up Saver...") saver = tf.train.Saver() #寫入logs為將來可視化做准備 summary_writer = tf.summary.FileWriter(FLAGS.logs_dir, sess.graph) sess.run(tf.global_variables_initializer()) ## 加載之前的checkpoint(檢查點日志)檢查點保存在logs文件里。 ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir) # sess:表示當前會話,之前保存的結果將被加載入這個會話 #.model_checkpoint_path:表示模型存儲的位置,不需要提供模型的名字,它會去查看checkpoint文件,看看最新的是誰,叫做什么。 if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print("Model restored...") #輸入指令開始訓練 if FLAGS.mode == "train": #MAX_ITERATION在這里指的是最大迭代的次數。 for itr in xrange(MAX_ITERATION): # 讀取訓練集的一個batch。 #調用BatchDatset里的next_batch函數該函數主要定義bachsize,還有結合bachsize對epoch初始化,開始到結束。 #FLAGS.batch_size是設置bachsize大小在該程序文件包開頭有設置。 train_images, train_annotations = train_dataset_reader.next_batch(FLAGS.batch_size) #將數據以字典形式讀入 feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85} # sess.run(train,feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85}) #執行優化器優化損失操作(train_op),網絡跑起來了 sess.run(train_op, feed_dict=feed_dict) #打印模型訓練過程訓練集損失每10步打印一次並可視化。 if itr % 10 == 0: train_loss, summary_str = sess.run([loss, summary_op], feed_dict=feed_dict) print("Step: %d, Train_loss:%g" % (itr, train_loss)) summary_writer.add_summary(summary_str, itr)#每10步搜集所有的寫文件 # if itr % 100==0: # print("epoch " + str(itr) + ": acc "+ str(accc) #每500步打印測試集送入模型后的預測損失保存生成的檢查點文件 if itr % 500 == 0: valid_images, valid_annotations = validation_dataset_reader.next_batch(FLAGS.batch_size) valid_loss = sess.run(loss, feed_dict={image: valid_images, annotation: valid_annotations, keep_probability: 1.0}) print("%s ---> Validation_loss: %g" % (datetime.datetime.now(), valid_loss)) saver.save(sess, FLAGS.logs_dir + "model.ckpt", itr) #visualize指令預測結果可視化過程。 elif FLAGS.mode == "visualize": valid_images, valid_annotations = validation_dataset_reader.get_random_batch(FLAGS.batch_size) pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations, keep_probability: 1.0}) valid_annotations = np.squeeze(valid_annotations, axis=3)#壓縮維度 #去掉pred索引為3位置的維度(我認為是通道數只留logits值) pred = np.squeeze(pred, axis=3) #循環迭代顯示並給原圖、標簽、預測標簽命名。str(5+itr)可以修改圖片的索引號,修改bachsize的值等 #於你的測試集圖片數就可以顯示所有的預測圖片。 for itr in range(FLAGS.batch_size): utils.save_image(valid_images[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5+itr)) utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5+itr)) utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="pred_" + str(5+itr)) print("Saved image: %d" % itr) #以下兩行程序為必須要有的關於程序啟動運行的。 if __name__ == "__main__": tf.app.run()

迭代5000次的實驗結果圖如下:

原始圖:                            

groundTruth:

預測圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM