tensorflow实战——tensorflow实现VGG

#%%
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from datetime import datetime
import math
import time
import tensorflow as tf
#tensor:多维向量
def conv_op(input_op, name, kh, kw, n_out, dh, dw, p):
    #参数详解:
    #input_op:输入的tensor;
    #name:这一层的名字
    #kh:卷积核的高
    #kw:卷积核的宽
    #n_out:卷积核数量,即输出通道数
    #dh:步长的高
    #dw:步长的宽
    #获取输入input_op的通道数
    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)
        #将bias转化成可训练的参数
        biases = tf.Variable(bias_init_val, trainable=True, name='b')
        #将卷积结果conv与bias相加
        z = tf.nn.bias_add(conv, biases)
        activation = tf.nn.relu(z, name=scope)
        #将创建卷积层是用到参数kernel和biases添加进参数列表
        p += [kernel, biases]
        #卷积层的输出
        return activation
#定义全连接层的创建函数
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')
        #对输入变量input_op与kernel做矩阵乘法并加上biases
        activation = tf.nn.relu_layer(input_op, kernel, biases, name=scope)
        p += [kernel, biases]
        return activation

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)

#创建网络
#keep_prob控制dropout比率的一个placeholder
def inference_op(input_op, keep_prob):
    #初始化参数列表
    p = []
    # assume input_op shape is 224x224x3

    # block 1 -- outputs 112x112x64
    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)

    # block 2 -- outputs 56x56x128
    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, dh=2, dw=2)

    # # block 3 -- outputs 28x28x256
    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, dh=2, dw=2)

    # block 4 -- outputs 14x14x512
    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=512, dh=1, dw=1, p=p)
    pool4 = mpool_op(conv4_3,   name="pool4",   kh=2, kw=2, dh=2, dw=2)

    # block 5 -- outputs 7x7x512
    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)

    # flatten 对卷及网络的输出结果进行扁平化
    shp = pool5.get_shape()
    flattened_shape = shp[1].value * shp[2].value * shp[3].value
    #将每个样本化为长度为7x7x512=25088的一维向量
    resh1 = tf.reshape(pool5, [-1, flattened_shape], name="resh1")

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

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

    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 i >= num_steps_burn_in:
            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
        #首先生成尺寸为224*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)

        init = tf.global_variables_initializer()

        config = tf.ConfigProto()
        config.gpu_options.allocator_type = 'BFC'
        sess = tf.Session(config=config)
        sess.run(init)

        time_tensorflow_run(sess, predictions, {keep_prob:1.0}, "Forward")
        #最后的全连接层的输出fc8的12loss
        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()

      

 

在进行图像分类项目时,将OpenCV与TensorFlow结合使用VGG16模型是一种常见的做法,而Python作为编程语言提供了便利的环境。要实现这一目标,首先需要了解图像预处理的过程,然后是模型的选择和训练,最后是源码的运行和测试。结合提供的资源《基于OpenCV和TensorFlow的生活垃圾图像分类项目源码解析》,可以详细掌握整个流程。 参考资源链接:[基于OpenCV和TensorFlow的生活垃圾图像分类项目源码解析](https://wenku.csdn.net/doc/4tdccs1gre) 在图像预处理阶段,使用OpenCV来处理输入图像,包括读取图像、进行二值化处理、轮廓识别和图像裁剪,以确保图像尺寸符合模型输入的要求。裁剪后的图像尺寸通常设置为224x224像素,以适应VGG16模型的输入格式。 接下来,利用TensorFlow框架来搭建和训练深度学习模型。VGG16模型因其优秀的图像识别能力而被广泛使用,但需要适当调整以适应特定的分类任务。在模型中加入批量归一化层可以帮助提高训练效率和模型的泛化能力。经过约15次迭代训练后,可以期待模型达到较高的训练集准确率和较为合理的测试集准确率。 最后,使用Python编程语言将源码运行起来,确保项目能够按照文档说明正确执行。运行过程中,可以利用提供的label文档来管理图像和标签,确保图像分类的准确性。此外,通过源码中的Demo演示,用户可以更直观地理解项目的不同组成部分和执行步骤。 综上所述,本资源提供了一个从图像预处理到模型训练再到源码运行的完整流程。对于那些希望深入理解并实践图像分类项目的读者来说,这是一个宝贵的学习资源。通过实践本项目,读者将能够掌握使用OpenCV进行图像处理,利用TensorFlow搭建VGG16模型,并通过Python编程实现整个图像分类系统的操作。 参考资源链接:[基于OpenCV和TensorFlow的生活垃圾图像分类项目源码解析](https://wenku.csdn.net/doc/4tdccs1gre)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值