《VGG in TensorFlow Demo》

本文详细介绍了VGG16卷积神经网络模型,包括其在图像分类任务中的应用、网络结构特点及训练方式。此外,还提供了VGG16在TensorFlow中的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文献来源: https://www.cs.toronto.edu/~frossard/post/vgg16/

VGG卷积神经网络是牛津大学在2014年提出来的模型。当这个模型被提出时,由于它的简洁性和实用性,马上成为了当时最流行的卷积神经网络模型。它在图像分类和目标检测任务中都表现出非常好的结果。在2014年的ILSVRC比赛中,VGG 在Top-5中取得了92.3%的正确率。

众所周知,VGG是一个良好的特征提取器,其与训练好的模型也经常被用来做其他事情,比如计算perceptual loss(风格迁移和超分辨率任务中),尽管现在resnet和inception网络等等具有很高的精度和更加简便的网络结构,但是在特征提取上,VGG一直是一个很好的网络,所以说,当你的某些任务上resnet或者inception等表现并不好时,不妨试一下VGG,或许会有意想不到的结果。

VGG之所以是一个很好的特征提取器,除了和它的网络结构有关,还和它的训练方式有关系,VGG并不是直接训练完成的,它使用了逐层训练的方法。

另外,VGG对于Alexnet来说,改进并不是很大,主要改进就在于使用了小卷积核,网络是分段卷积网络,通过maxpooling过度,同时网络更深更宽。

 

VGG16命名由来即该神经网络层结构为:13层卷积层,3层链接层。

运行环境:python3,Ubuntu

文件列表:

   1:模型权重:vgg16_weights.npz

  2:TensorFlow模型:vgg16.py

  3:类名列表:imagenet_classes.py

  4:输入实例:m1.jpg

代码实例:

  vgg16.py

  

########################################################################################

# Davi Frossard, 2016                                                                  #

# VGG16 implementation in TensorFlow                                                   #

# Details:                                                                             #

# http://www.cs.toronto.edu/~frossard/post/vgg16/                                      #

#                                                                                      #

# Model from https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md     #

# Weights from Caffe converted using https://github.com/ethereon/caffe-tensorflow      #

########################################################################################



import tensorflow as tf

import numpy as np

from scipy.misc import imread, imresize

from imagenet_classes import class_names





class vgg16:

    def __init__(self, imgs, weights=None, sess=None):

        self.imgs = imgs

        self.convlayers()

        self.fc_layers()

        self.probs = tf.nn.softmax(self.fc3l)

        if weights is not None and sess is not None:

            self.load_weights(weights, sess)





    def convlayers(self):

        self.parameters = []



        # zero-mean input

        with tf.name_scope('preprocess') as scope:

            mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[1, 1, 1, 3], name='img_mean')

            images = self.imgs-mean



        # conv1_1

        with tf.name_scope('conv1_1') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv1_1 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv1_2

        with tf.name_scope('conv1_2') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 64], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv1_1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv1_2 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # pool1

        self.pool1 = tf.nn.max_pool(self.conv1_2,

                               ksize=[1, 2, 2, 1],

                               strides=[1, 2, 2, 1],

                               padding='SAME',

                               name='pool1')



        # conv2_1

        with tf.name_scope('conv2_1') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.pool1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv2_1 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv2_2

        with tf.name_scope('conv2_2') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 128], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv2_1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv2_2 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # pool2

        self.pool2 = tf.nn.max_pool(self.conv2_2,

                               ksize=[1, 2, 2, 1],

                               strides=[1, 2, 2, 1],

                               padding='SAME',

                               name='pool2')



        # conv3_1

        with tf.name_scope('conv3_1') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 256], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.pool2, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv3_1 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv3_2

        with tf.name_scope('conv3_2') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv3_1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv3_2 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv3_3

        with tf.name_scope('conv3_3') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv3_2, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv3_3 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # pool3

        self.pool3 = tf.nn.max_pool(self.conv3_3,

                               ksize=[1, 2, 2, 1],

                               strides=[1, 2, 2, 1],

                               padding='SAME',

                               name='pool3')



        # conv4_1

        with tf.name_scope('conv4_1') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.pool3, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv4_1 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv4_2

        with tf.name_scope('conv4_2') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv4_1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv4_2 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv4_3

        with tf.name_scope('conv4_3') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv4_2, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv4_3 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # pool4

        self.pool4 = tf.nn.max_pool(self.conv4_3,

                               ksize=[1, 2, 2, 1],

                               strides=[1, 2, 2, 1],

                               padding='SAME',

                               name='pool4')



        # conv5_1

        with tf.name_scope('conv5_1') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.pool4, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv5_1 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv5_2

        with tf.name_scope('conv5_2') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv5_1, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv5_2 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # conv5_3

        with tf.name_scope('conv5_3') as scope:

            kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,

                                                     stddev=1e-1), name='weights')

            conv = tf.nn.conv2d(self.conv5_2, kernel, [1, 1, 1, 1], padding='SAME')

            biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),

                                 trainable=True, name='biases')

            out = tf.nn.bias_add(conv, biases)

            self.conv5_3 = tf.nn.relu(out, name=scope)

            self.parameters += [kernel, biases]



        # pool5

        self.pool5 = tf.nn.max_pool(self.conv5_3,

                               ksize=[1, 2, 2, 1],

                               strides=[1, 2, 2, 1],

                               padding='SAME',

                               name='pool4')



    def fc_layers(self):

        # fc1

        with tf.name_scope('fc1') as scope:

            shape = int(np.prod(self.pool5.get_shape()[1:]))

            fc1w = tf.Variable(tf.truncated_normal([shape, 4096],

                                                         dtype=tf.float32,

                                                         stddev=1e-1), name='weights')

            fc1b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32),

                                 trainable=True, name='biases')

            pool5_flat = tf.reshape(self.pool5, [-1, shape])

            fc1l = tf.nn.bias_add(tf.matmul(pool5_flat, fc1w), fc1b)

            self.fc1 = tf.nn.relu(fc1l)

            self.parameters += [fc1w, fc1b]



        # fc2

        with tf.name_scope('fc2') as scope:

            fc2w = tf.Variable(tf.truncated_normal([4096, 4096],

                                                         dtype=tf.float32,

                                                         stddev=1e-1), name='weights')

            fc2b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32),

                                 trainable=True, name='biases')

            fc2l = tf.nn.bias_add(tf.matmul(self.fc1, fc2w), fc2b)

            self.fc2 = tf.nn.relu(fc2l)

            self.parameters += [fc2w, fc2b]



        # fc3

        with tf.name_scope('fc3') as scope:

            fc3w = tf.Variable(tf.truncated_normal([4096, 1000],

                                                         dtype=tf.float32,

                                                         stddev=1e-1), name='weights')

            fc3b = tf.Variable(tf.constant(1.0, shape=[1000], dtype=tf.float32),

                                 trainable=True, name='biases')

            self.fc3l = tf.nn.bias_add(tf.matmul(self.fc2, fc3w), fc3b)

            self.parameters += [fc3w, fc3b]



    def load_weights(self, weight_file, sess):

        weights = np.load(weight_file)

        keys = sorted(weights.keys())

        for i, k in enumerate(keys):

            print(i, k, np.shape(weights[k]))

            sess.run(self.parameters[i].assign(weights[k]))



if __name__ == '__main__':

    sess = tf.Session()

    imgs = tf.placeholder(tf.float32, [None, 224, 224, 3])

    vgg = vgg16(imgs, 'vgg16_weights.npz', sess)



    img1 = imread('m1.jpg', mode='RGB')

    img1 = imresize(img1, (224, 224))



    prob = sess.run(vgg.probs, feed_dict={vgg.imgs: [img1]})[0]

    preds = (np.argsort(prob)[::-1])[0:5]

    for p in preds:

        print (class_names[p], prob[p])

  效果展示:

  

  由图可见,识别效果还是可以滴!

  

  关于VGG16具体实现见链接:https://blog.youkuaiyun.com/errors_in_life/article/details/65950699

  另一详细介绍见:http://www.360doc.com/content/17/0624/10/10408243_666125650.shtml

### 回答1: VGG16是一种深度卷积神经网络模型,TensorFlow 2是一种深度学习框架。VGG16 TensorFlow 2代码是指使用TensorFlow 2实现VGG16模型的代码。这种代码通常包括模型定义、数据预处理、训练和测试等部分。通过使用VGG16 TensorFlow 2代码,可以快速构建和训练一个高效的图像分类模型。 ### 回答2: VGG16是一个使用卷积神经网络(CNN)的深度学习模型,由牛津大学计算机视觉组(Visual Geometry Group)开发而来。该模型在ImageNet数据集上获得了出色的表现,在计算机视觉领域有着广泛的应用。 TensorFlow是一个非常受欢迎的机器学习框架。它提供了一个易于使用的界面,可以快速开发和训练深度学习模型。与其他机器学习框架相比,TensorFlow提供了更快的训练速度和更好的可伸缩性,有很多优点。 VGG16 TensorFlow2代码是使用TensorFlow2库实现的VGG16模型。TensorFlow2是TensorFlow的最新版本,相比于TensorFlow1.x版本有更好的易用性和更好的性能。此版本还引入了KerasAPI,使得使用TensorFlow变得更加容易。 VGG16 TensorFlow2代码的实现包括以下步骤: 1.导入必要的库:TensorFlow2.0,numpy,pandas和matplotlib等。 2.加载数据集:在这个例子中,数据集是CIFAR-10。 3.数据预处理:对图像进行标准化,并将标签转换为one-hot矩阵。 4.定义模型:使用Sequential模型类创建模型,并将层添加到模型中。 5.训练模型:使用compile方法编译模型,并使用fit方法训练模型。 6.评估模型:使用evaluate方法评估模型在测试集上的性能。 VGG16 TensorFlow2代码的优点包括易于使用、高效和可扩展性。此外,由于TensorFlow2具有更易于使用的API,所以即使是初学者也可以轻松地使用此代码实现VGG16模型。由于VGG16已被证明在很多计算机视觉任务中表现出了出色的性能,因此VGG16 TensorFlow2代码可以在物体检测、图像分类、图像分割等领域应用。 ### 回答3: VGG16是一种经典的深度卷积神经网络,由19个学习层组成。它是在2014年ILSVRC(ImageNet Large Scale Visual Recognition Challenge)挑战赛上获得了第一名。VGG16是一个非常强大的模型,可以识别图像中的不同物体类别。 TensorFlow 2版本的VGG16代码是一个对原始VGG16模型的实现,它包含了基本的层和网络结构。这个实现使用了Sequential模型结构,就是一个个添加层的方式组成一个模型。在这个模型中,VGG16的基本结构从输入层到输出层依次为:Convolutional层、ReLU层、MaxPooling层和完全连接层。VGG16模型中的卷积层和池化层是如此之多,导致整个模型的可训练参数非常多,约为14亿个。这就需要使用GPU来进行训练,提高训练的速度。 VGG16模型的主要作用是图像分类,可以将其用于图像分类任务中。使用VGG16模型可以获得非常良好的图像分类效果。例如,在ImageNet数据集上进行训练,VGG16模型的分类精度可以达到92%以上。 总之,TensorFlow 2版本的VGG16代码是一个强大的模型实现,该模型可以用于图像分类等视觉任务中。它是通过卷积神经网络的层级组合来构造的,使用GPU进行训练,可以获得非常好的分类效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值