微信公众号:龙跃十二
我是小玉,一个平平无奇的小天才!
猫狗大战——基于TensorFlow的猫狗识别(1)
猫狗大战——基于TensorFlow的猫狗识别(2)
将数据导入以后,我们经过一系列的处理得到了最终打乱的图像和标签,这里都是以列表的形式输出,接下来,我们需要建立一个模型来对图像数据进行识别,在这里我们选择使用CNN(卷积神经网络)模型。
构造卷积神经网络,网络结构为:(卷积层+池化层) 2 +(全连接层) 2+ Softmax层;每个网络层都使用with tf.variable_scope(“name”)语句,这其实是TensorFlow中的变量作用域机制;在变量作用域内,使用tf.get_variable(, , ): 创建变量。
文件名:model.py
模块的导入:
import tensorflow as tf
- conv1 卷积层 1
- pooling1_lrn 池化层 1
- conv2 卷积层 2
- pooling2_lrn 池化层 2
- local3 全连接层 1
- local4 全连接层 2
- softmax
模型设计:
(1)模型的创建:
def inference(images, batch_size, n_classess):
"""
第一个卷积层
16个3x3的卷积核(3通道),padding=’SAME’,表示padding后卷积的图与原图尺寸一致,激活函数relu()
"""
# tf.variable_scope() 主要结合 tf.get_variable() 来使用,实现变量共享。下次调用不用重新产生,这样可以保存参数
with tf.variable_scope('conv1') as scope: #初始化权重,[3,3,3,16]
weights = tf.get_variable('weights', shape = [3, 3, 3, 16], dtype = tf.float32,
initializer = tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
#初始化偏置,16个
biases = tf.get_variable('biases', shape=[16], dtype = tf.float32,
initializer = tf.constant_initializer(0.1))
conv = tf.nn.conv2d(images, weights, strides=[1,1,1,1], padding='SAME')
# 将偏置加在所得的值上面
pre_activation = tf.nn.bias_add(conv, biases)
# 将计算结果通过relu激活函数完成去线性化
conv1 = tf.nn.relu(pre_activation, name= scope.name)
"""
池化层1
3x3最大池化,步长strides为2,池化后执行lrn()操作,局部响应归一化,对训练有利。
"""
with tf.variable_scope('pooling1_lrn') as scope:
# tf.nn.max_pool