tensorflow-slim搭建vgg16

背景:slim是16年推出的,作为tensorflow的高级库。将许多重复的操作进行封装,能大幅度减少代码量,本文便是基于slim实现了vgg16网络的搭建。

常用函数:参考  点击打开链接

完整定义:

import tensorflow as tf
import tensorflow.contrib.slim as slim
#inputs:秩为N+2的tensor,如 [batch_size] + input_spatial_shape + [in_channels]
def VGG_16(inputs):
    with slim.arg_scope([slim.conv2d,slim.fully_connected],activation_fn = tf.nn.relu,weights_initializer = tf.truncated_normal_initializer(0.0,0.01),weights_regularizer = slim.l2_regularizer(0.0005)):
        net = slim.repeat(inputs,2,slim.conv2d,64,[3,3],scope = 'conv1')
        net = slim.max_pool2d(net,[2,2],scope = 'pool1')
        net = slim.repeat(net,2,slim.conv2d,128,[3,3],scope = 'conv2')
        net = slim.max_pool2d(net,[2,2],scope = 'pool2')
        net = slim.repeat(net,2,slim.conv2d,256,[3,3],scope= 'conv3')
        net = slim.max_pool2d(net,[2,2],scope = 'pool3')
        net = slim.repeat(net,3,slim.conv2d,512,[3,3],scope = 'conv4')
        net = slim.max_pool2d(net,[2,2],scope = 'pool4');
        net = slim.repeat(net,3,slim.conv2d,512,[3,3],scope = 'conv5')
        net = slim.max_pool2d(net,[2,2],scope = 'pool5');
        #全连接
        net = slim.flatten(net,scope='flat5')
        net = slim.fully_connected(net,4096,scope = 'fc6')
        net = slim.fully_connected(net,4096,scope = 'fc7')
        net = slim.fully_connected(net,1000,scope = 'fc8')
        softmax = tf.nn.softmax(net)
        pred = tf.argmax(softmax,1) 
    return pred,softmax,net

你可能感兴趣的:(深度学习)