欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TensorFlow实现经典深度学习网络(2):TensorFlow实现VGGNet

程序员文章站 2024-03-14 09:56:46
...

TensorFlow实现经典深度学习网络(2):TensorFlow实现VGGNet


        VGGNet是经典的深度学习网络之一,由牛津大学的视觉几何组(Visual Geometry Group)提出,是ILSVRC-2014中定位任务第一名和分类任务第二名(top-5错误率7.3%,19层神经网络)。其探索了卷积神经网络的深度与其性能之间的关系,拓展性很强,通过反复堆叠3×3的小型卷积核和2×2的最大池化层,成功构筑了16~19层深的卷积神经网络,增加网络深度可以有效提升模型的效果,而且VGGNet对其他数据集具有很好的泛化能力。到目前为止,VGGNet依然常被用来提取图像特征。

TensorFlow实现经典深度学习网络(2):TensorFlow实现VGGNet

TensorFlow实现经典深度学习网络(2):TensorFlow实现VGGNet

        VGGNet论文中全部使用来3×3的卷积核和2×2的池化核,通过不断加深网络结构来提升性能。上图为VGGNet各级别的网络结构图和各级别网络参数量。VGGNet拥有5段卷积,每一段有2~3个卷积层,同时每段尾部连有最大池化层来缩小图片尺寸。VGGNet为了在公平的原则下探究网络深度对模型精确度的影响,所有卷积层有相同的配置,即卷积核大小为3x3,步长为1,填充为1;共有5个最大池化层,大小都为2x2,步长为2;共有三个全连接层,前两层都有4096通道,第三层共1000路及代表1000个标签类别;最后一层为softmax层;所有隐藏层后都带有ReLU非线性**函数;经过实验证明,AlexNet中提出的局部响应归一化(LRN)对性能提升并没有什么帮助,而且还浪费了内存的计算的损耗。可以说,VGGNet使得CNN对特征的学习能力更强。

        VGGNet的突出影响包括:

       (1)一个大卷积核分解成连续多个小卷积核;

       (2)减少参数,降低计算,增加深度;

       (3)继承AlexNet结构特点:简单,有效;

       (4)网络改造的首选基础网络

        因使用ImageNet数据集非常耗时,因此本文会对完整的VGGNet网络进行速度测试,评测forward耗时和backward耗时。若读者感兴趣,可自行下载ImageNet数据集进行训练测试。

        在准备工作就绪后,我们就可以搭建VGGNet网络,也就是版本D,其他版本读者可仿照以下代码自行修改。以下代码是本人根据自己的理解整理而成,并亲自验证,代码中标有自己理解所得的注释,若有错误请指正。

# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# VGGNet-16
# 导入常用库,载入TensorFlow
from datetime import datetime
import math
import time
import tensorflow as tf

# 创建卷积层并把本层的参数存入参数列表
def conv_op(input_op, name, kh, kw, n_out, dh, dw, p):
    n_in = input_op.get_shape()[-1].value

    with tf.name_scope(name) as scope:
        kernel = tf.get_variable(scope + "w", shape=[kh, kw, n_in, n_out],
                                 dtype=tf.float32,
                                 initializer=tf.contrib.layers.xavier_initializer_conv2d())

        # 对input_op进行卷积处理
        conv = tf.nn.conv2d(input_op, kernel, (1, dh, dw, 1), padding='SAME')
        bias_init_val = tf.constant(0.0, shape=[n_out], dtype=tf.float32)
        biases = tf.Variable(bias_init_val, trainable=True, name='b')
        z = tf.nn.bias_add(conv, biases)
        activation = tf.nn.relu(z, name=scope)
        p += [kernel, biases]
        return activation

# 定义全连接层创建函数fc_op
def fc_op(input_op, name, n_out, p):
    n_in = input_op.get_shape()[-1].value

    with tf.name_scope(name) as scope:
        kernel = tf.get_variable(scope + "w", shape=[n_in, n_out],
                                 dtype=tf.float32,
                                 initializer=tf.contrib.layers.xavier_initializer())
        biases = tf.Variable(tf.constant(0.1, shape= [n_out],
                                         dtype=tf.float32), name='b')
        activation = tf.nn.relu_layer(input_op, kernel, biases, name=scope)
        p += [kernel, biases]
        return activation

# 定义最大池化层创建函数mpool_op
def mpool_op(input_op, name, kh, kw, dh, dw):
    return tf.nn.max_pool(input_op,
                          ksize=[1, kh, kw, 1],
                          strides=[1, dh, dw, 1],
                          padding='SAME',
                          name=name)

# 创建VGGNet-16
def inference_op(input_op, keep_prob):

    p = []

    # conv1
    conv1_1 = conv_op(input_op, name="conv1_1", kh=3, kw=3, n_out=64, dh=1, dw=1, p=p)
    conv1_2 = conv_op(conv1_1, name="conv1_2", kh=3, kw=3, n_out=64, dh=1, dw=1, p=p)
    pool1 = mpool_op(conv1_2, name="pool1", kh=2, kw=2, dw=2, dh=2)

    # conv2
    conv2_1 = conv_op(pool1, name="conv2_1", kh=3, kw=3, n_out=128, dh=1, dw=1, p=p)
    conv2_2 = conv_op(conv2_1, name="conv2_2", kh=3, kw=3, n_out=128, dh=1, dw=1, p=p)
    pool2 = mpool_op(conv2_2, name="pool2", kh=2, kw=2, dw=2, dh=2)

    # conv3
    conv3_1 = conv_op(pool2, name="conv3_1", kh=3, kw=3, n_out=256, dh=1, dw=1, p=p)
    conv3_2 = conv_op(conv3_1, name="conv3_2", kh=3, kw=3, n_out=256, dh=1, dw=1, p=p)
    conv3_3 = conv_op(conv3_2, name="conv3_3", kh=3, kw=3, n_out=256, dh=1, dw=1, p=p)
    pool3 = mpool_op(conv3_3, name="pool3", kh=2, kw=2, dw=2, dh=2)

    # conv4
    conv4_1 = conv_op(pool3, name="conv4_1", kh=3, kw=3, n_out=512, dh=1, dw=1, p=p)
    conv4_2 = conv_op(conv4_1, name="conv4_2", kh=3, kw=3, n_out=512, dh=1, dw=1, p=p)
    conv4_3 = conv_op(conv4_2, name="conv4_3", kh=3, kw=3, n_out=2512, dh=1, dw=1, p=p)
    pool4 = mpool_op(conv4_3, name="pool4", kh=2, kw=2, dw=2, dh=2)

    # conv5
    conv5_1 = conv_op(pool4, name="conv5_1", kh=3, kw=3, n_out=512, dh=1, dw=1, p=p)
    conv5_2 = conv_op(conv5_1, name="conv5_2", kh=3, kw=3, n_out=512, dh=1, dw=1, p=p)
    conv5_3 = conv_op(conv5_2, name="conv5_3", kh=3, kw=3, n_out=512, dh=1, dw=1, p=p)
    pool5 = mpool_op(conv5_3, name="pool5", kh=2, kw=2, dw=2, dh=2)

    # 将conv5输出结果扁平化
    shp = pool5.get_shape()
    flattened_shape = shp[1].value * shp[2].value * shp[3].value
    resh1 = tf.reshape(pool5, [-1, flattened_shape], name="resh1")

    # fc6
    fc6 = fc_op(resh1, name="fc6", n_out=4096, p=p)
    fc6_drop = tf.nn.dropout(fc6, keep_prob, name="fc6_drop")

    # fc7
    fc7 = fc_op(fc6_drop, name="fc7", n_out=4096, p=p)
    fc7_drop = tf.nn.dropout(fc7, keep_prob, name="fc7_drop")

    # fc8
    fc8 = fc_op(fc7_drop, name="fc8", n_out=1000, p=p)
    softmax = tf.nn.softmax(fc8)
    predictions = tf.argmax(softmax, 1)
    return predictions, softmax, fc8, p

# 评测
def time_tensorflow_run(session, target, feed, info_string):
    num_steps_burn_in = 10
    total_duration = 0.0
    total_duration_squared = 0.0
    for i in range(num_batches + num_steps_burn_in):
        start_time = time.time()
        _ = session.run(target, feed_dict=feed)
        duration = time.time() - start_time
        if not i % 10:
            print('%s: step %d, duration = %.3f' % (datetime.now(), i - num_steps_burn_in, duration))
            total_duration += duration
            total_duration_squared += duration * duration
    mn = total_duration / num_batches
    vr = total_duration_squared / num_batches - mn *mn
    sd = math.sqrt(vr)
    print('%s: %s across %d steps, %.3f +/- %.3f sec / batch' %
          (datetime.now(), info_string, num_batches, mn, sd))

# 定义评测主函数
def run_benchmark():
    with tf.Graph().as_default():
        image_size = 224
        images = tf.Variable(tf.random_normal([batch_size,
                                               image_size,
                                               image_size, 3],
                                              dtype=tf.float32,
                                              stddev=1e-1))

        keep_prob = tf.placeholder(tf.float32)
        predictions, softmax, fc8, p = inference_op(images, keep_prob)

        # 创建Session并初始化全局参数
        init = tf.global_variables_initializer()
        sess = tf.Session()
        sess.run(init)

        time_tensorflow_run(sess, predictions, {keep_prob: 1.0}, "Forward")
        objective = tf.nn.l2_loss(fc8)
        grad = tf.gradients(objective, p)
        time_tensorflow_run(sess, grad, {keep_prob: 0.5}, "Forward-backward")

batch_size = 32
num_batches = 100
run_benchmark()
        运行程序,我们会看到如下的程序显示(部分)

2017-10-13 15:26:22.435496: step -10, duration = 14.238
2017-10-13 15:28:45.836558: step 0, duration = 14.355
2017-10-13 15:31:08.099205: step 10, duration = 14.220
2017-10-13 15:33:30.337682: step 20, duration = 14.211
2017-10-13 15:35:52.644435: step 30, duration = 14.302
2017-10-13 15:38:15.698386: step 40, duration = 14.325
2017-10-13 15:40:38.672939: step 50, duration = 14.256
2017-10-13 15:43:01.125935: step 60, duration = 14.209
2017-10-13 15:45:23.317328: step 70, duration = 14.254
2017-10-13 15:47:45.705173: step 80, duration = 14.437
2017-10-13 15:50:13.805813: step 90, duration = 14.440
2017-10-13 15:52:26.331622: Forward across 100 steps, 1.572 +/- 4.473 sec / batch
2017-10-13 15:53:12.896681: step -10, duration = 46.497
2017-10-13 16:00:58.813022: step 0, duration = 46.705
2017-10-13 16:08:44.818871: step 10, duration = 46.518
2017-10-13 16:16:35.558625: step 20, duration = 46.913
2017-10-13 16:24:30.725427: step 30, duration = 46.850
2017-10-13 16:32:18.516636: step 40, duration = 46.793

        以上为程序运行过程中显示的VGGNet结构以及forward、backword运算时间。

        至此,TensorFlow实现VGGNet的工作就完成了。VGG系列的卷积神经网络在ILSVRC2014比赛中最终达到来7.3%的错误率,相比AlexNet进步非常大,成为一种经典的卷积神经网络。后续,我将和大家探讨其他的经典深度学习网络。

       在后续工作中,我将继续为大家展现TensorFlow和深度学习网络带来的无尽乐趣,我将和大家一起探讨深度学习的奥秘。当然,如果你感兴趣,我的Weibo将与你一起分享最前沿的人工智能、机器学习、深度学习与计算机视觉方面的技术。