分享

学习TensorFlow,调用预训练好的网络(Alex, VGG, ResNet etc)

 雪柳花明 2017-03-17

       视觉问题引入深度神经网络后,针对端对端的训练和预测网络,可以看是特征的表达和任务的决策问题(分类,回归等)。当我们自己的训练数据量过小时,往往借助牛人已经预训练好的网络进行特征的提取,然后在后面加上自己特定任务的网络进行调优。目前,ILSVRC比赛(针对1000类的分类问题)所使用数据的训练集126万张图像,验证集5万张,测试集10万张(标注未公布),大家一般使用这个比赛的前几名的网络来搭建自己特定任务的神经网络。

      本篇博文主要简单讲述怎么使用TensorFlow调用预训练好的VGG网络,其他的网络(如Alex, ResNet等)也是同样的套路。分为三个部分:第一部分下载网络架构定义以及权重参数,第二部分是如何调用预训练网络中的feature map,第三部分给出参考资料。注:资料是学习查找整理而得,理解有误的地方,请多多指正~

一、下载网络架构定义以及权重参数

https://github.com/leihe001/tensorflow-vgg  训练和测试网络的定义

https:///#!YU1FWJrA!O1ywiCS2IiOlUCtCpI6HTJOMrneN-Qdv3ywQP5poecM VGG16

https:///#!xZ8glS6J!MAnE91ND_WyfZ_8mvkuSa2YcA7q-1ehfSm-Q1fxOvvs VGG19


二、调用预训练网络中的feature map(以VGG16为例)

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. import inspect  
  2. import os  
  3.   
  4. import numpy as np  
  5. import tensorflow as tf  
  6. import time  
  7.   
  8. VGG_MEAN = [103.939, 116.779, 123.68]  
  9.   
  10.   
  11. class Vgg16:  
  12.     def __init__(self, vgg16_npy_path=None):  
  13.         if vgg16_npy_path is None:  
  14.             path = inspect.getfile(Vgg16)  
  15.             path = os.path.abspath(os.path.join(path, os.pardir))  
  16.             path = os.path.join(path, "vgg16.npy")  
  17.             vgg16_npy_path = path  
  18.             print path  
  19. <span style="white-space:pre">  </span><span style="color:#ff0000;"># 加载网络权重参数</span>  
  20.         self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()  
  21.         print("npy file loaded")  
  22.   
  23.     def build(self, rgb):  
  24.         """ 
  25.         load variable from npy to build the VGG 
  26.  
  27.         :param rgb: rgb image [batch, height, width, 3] values scaled [0, 1] 
  28.         """  
  29.   
  30.         start_time = time.time()  
  31.         print("build model started")  
  32.         rgb_scaled = rgb * 255.0  
  33.   
  34.         # Convert RGB to BGR  
  35.         red, green, blue = tf.split(3, 3, rgb_scaled)  
  36.         assert red.get_shape().as_list()[1:] == [224, 224, 1]  
  37.         assert green.get_shape().as_list()[1:] == [224, 224, 1]  
  38.         assert blue.get_shape().as_list()[1:] == [224, 224, 1]  
  39.         bgr = tf.concat(3, [  
  40.             blue - VGG_MEAN[0],  
  41.             green - VGG_MEAN[1],  
  42.             red - VGG_MEAN[2],  
  43.         ])  
  44.         assert bgr.get_shape().as_list()[1:] == [224, 224, 3]  
  45.   
  46.         self.conv1_1 = self.conv_layer(bgr, "conv1_1")  
  47.         self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")  
  48.         self.pool1 = self.max_pool(self.conv1_2, 'pool1')  
  49.   
  50.         self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")  
  51.         self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")  
  52.         self.pool2 = self.max_pool(self.conv2_2, 'pool2')  
  53.   
  54.         self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")  
  55.         self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")  
  56.         self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")  
  57.         self.pool3 = self.max_pool(self.conv3_3, 'pool3')  
  58.   
  59.         self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")  
  60.         self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")  
  61.         self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")  
  62.         self.pool4 = self.max_pool(self.conv4_3, 'pool4')  
  63.   
  64.         self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")  
  65.         self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")  
  66.         self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")  
  67.         self.pool5 = self.max_pool(self.conv5_3, 'pool5')  
  68.   
  69.         self.fc6 = self.fc_layer(self.pool5, "fc6")  
  70.         assert self.fc6.get_shape().as_list()[1:] == [4096]  
  71.         self.relu6 = tf.nn.relu(self.fc6)  
  72.   
  73.         self.fc7 = self.fc_layer(self.relu6, "fc7")  
  74.         self.relu7 = tf.nn.relu(self.fc7)  
  75.   
  76.         self.fc8 = self.fc_layer(self.relu7, "fc8")  
  77.   
  78.         self.prob = tf.nn.softmax(self.fc8, name="prob")  
  79.   
  80.         self.data_dict = None  
  81.         print("build model finished: %ds" % (time.time() - start_time))  
  82.   
  83.     def avg_pool(self, bottom, name):  
  84.         return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)  
  85.   
  86.     def max_pool(self, bottom, name):  
  87.         return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)  
  88.   
  89.     def conv_layer(self, bottom, name):  
  90.         with tf.variable_scope(name):  
  91.             filt = self.get_conv_filter(name)  
  92.   
  93.             conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')  
  94.   
  95.             conv_biases = self.get_bias(name)  
  96.             bias = tf.nn.bias_add(conv, conv_biases)  
  97.   
  98.             relu = tf.nn.relu(bias)  
  99.             return relu  
  100.   
  101.     def fc_layer(self, bottom, name):  
  102.         with tf.variable_scope(name):  
  103.             shape = bottom.get_shape().as_list()  
  104.             dim = 1  
  105.             for d in shape[1:]:  
  106.                 dim *= d  
  107.             x = tf.reshape(bottom, [-1, dim])  
  108.   
  109.             weights = self.get_fc_weight(name)  
  110.             biases = self.get_bias(name)  
  111.   
  112.             # Fully connected layer. Note that the '+' operation automatically  
  113.             # broadcasts the biases.  
  114.             fc = tf.nn.bias_add(tf.matmul(x, weights), biases)  
  115.   
  116.             return fc  
  117.   
  118.     def get_conv_filter(self, name):  
  119.         return tf.constant(self.data_dict[name][0], name="filter")  
  120.   
  121.     def get_bias(self, name):  
  122.         return tf.constant(self.data_dict[name][1], name="biases")  
  123.   
  124.     def get_fc_weight(self, name):  
  125.         return tf.constant(self.data_dict[name][0], name="weights")  

以上是VGG16网络的定义,假设我们现在输入图像image,打算做分割,那么我们可以使用端对端的全卷积网络进行训练和测试。针对这个任务,我们只需要输出pool5的feature map即可。

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. #以上你的网络定义,初始化方式,以及数据预处理...  
  2.   
  3. vgg = vgg16.Vgg16()  
  4. vgg.build(image)  
  5. feature_map = vgg.pool5  
  6. mask = yournetwork(feature_map)  
  7.   
  8. #以下定义loss,学习率策略,然后train...  


三、参考资料

https://github.com/leihe001/tensorflow-vgg

https://github.com/leihe001/tfAlexNet

https://github.com/leihe001/tensorflow-resnet


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多