import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # TensorFlow中提供的演示数据
"""
卷积神经网络重要概念:分为卷积层,激活,池化层,全连接层
卷积层中的卷积核包含权重系数,而池化层不包含权重系数
卷积层卷积过程:
过滤器(观察窗口):
组成:
大小(奇数,1*1、3*3、5*5、13*13),移动步长,
作用:
通过观察窗口去扫描一张图片,不管是单通道还是3通道图片,一个过滤器最后只会返回一张图片
零填充:当移动后超出图片大小,有两种解决方式,一种是直接越过放弃不能扫描的部分,二是对图片进行零填充到满足扫描
案列:一张[28,30,3]的图片经过大小5*5、步长3、零填充4的n个过滤扫描后变成:[((28-5+2*4)/3)+1, ((30-窗口大小+2倍零填充的大小)/步长)+1, n]
卷积神经的激活函数(Relu):f(x) = max(0, x),增加网格的非线性分割能力,相对于sigmoid函数,计算量小,而且sigmoid函数在反向传播的时候容易引起梯度爆炸
池化层(pooling):特征提取,去掉feature map 中不重要的样本,减少参数数量。pooling方法很多,常用的max pooling,max pooling方法用2*2步长2的窗口去扫描卷积后的图片,逐一取窗口内最大的数,每移动一次取一次,一张4*4的图片经过扫描以后就会变成2*2的图片,也会有零填充的需要,池化后的图片大小计算方式和上面的案例是一直的
"""
# 定义一个随机初始化权重函数
def weight_variables(shape):
w = tf.Variable(tf.random_normal(shape=shape, mean=0.0, stddev=1.0))
return w
# 定义一个随机初始化偏置函数
def bias_variables(shape):
b = tf.Variable(tf.constant(0.0, shape=shape))
return b
def model():
"""自定义卷积模型"""
# 1.建立数据的占位符 特征值X [None, 784] 目标值y_true [None, 10]
with tf.variable_scope("data"):
# None代表不确定的样本数
x = tf.placeholder(tf.float32, [None, 784])
y_true = tf.placeholder(tf.float32, [None, 10])
# 第一个卷积层,卷积:5*5*1,32个,strides=1,激活:tf.nn.relu 池化
with tf.variable_scope("conv1"):
# 随机初始化权重1是输入通道,32是输出通道,偏置[32]
w_conv1 = weight_variables([5, 5, 1, 32])
b_conv1 = bias_variables([32])
# 对x进行形状改变[None, 784] ==> [None, 28, 28, 1]
x_reshape = tf.reshape(x, [-1, 28, 28, 1])
'''卷积层API
tf.nn.conv2d(input, filter=, strides=,padding=,name=,)
input:给定的输入张量,具有[batch, height, width, channel],类型为float32,64
filter:指定过滤器大小,[filter_height, filter_width, in_channel, out_channels]
strides:步长,[1, stride, stride, 1]
padding:SAME或者VALID,VALID表示超出部分舍弃,SAME表示填充,使得变化后的height和weight一样大
'''
# [None, 28, 28, 1] ==> [None, 28, 28, 32]
x_relu1 = tf.nn.relu(tf.nn.conv2d(x_reshape, w_conv1, strides=[1, 1, 1, 1], padding="SAME") + b_conv1)
# 池化 2*2,strides [None, 28, 28, 32] ==> [None, 14, 14, 32],第一个参数[batch, height, width, channel],ksize池化窗口大小[1, ksize, ksize, 1],strides步长[1, stride, stride, 1],这里的padding跟卷积核的不一样,只是单纯的不够进行填充
x_pool1 = tf.nn.max_pool(x_relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 第二个卷积层
with tf.variable_scope("conv2"):
# 随随机初始化变量,权重:[5, 5, 32, 64]
w_conv2 = weight_variables([5, 5, 32, 64])
b_conv2 = bias_variables([64])
# 卷积,激活,池化
# [None, 14, 14, 32]==>[None, 14, 14, 64]
x_relu2 = tf.nn.relu(tf.nn.conv2d(x_pool1, w_conv2, strides=[1, 1, 1, 1], padding="SAME") + b_conv2)
# 池化 2*2,strides [None, 14, 14, 64] ==> [None, 7, 7, 64]
x_pool2 = tf.nn.max_pool(x_relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 全连接层,[None, 7, 7, 64]==>[None, 7*7*64]*[7*7*64, 10] + [10] = [None, 10]
with tf.variable_scope(""):
# 随机初始化权重
w_fc = weight_variables([7*7*64, 10])
b_fc = bias_variables([10])
# 修改形状,[None, 7, 7, 64]==>[None, 7*7*64]
x_fc_reshape = tf.reshape(x_pool2, [-1, 7*7*64])
# 进行矩阵运算得出每个样本的10个结果
y_predict = tf.matmul(x_fc_reshape, w_fc) + b_fc
return x, y_true, y_predict
def con_vfc():
# 获取真实数据
mnist = input_data.read_data_sets("./mnist/input_data/", one_hot=True)
# 定义模型,得出输出
x, y_true, y_predict = model()
# 3.求所有样本的损失,然后求损失
with tf.variable_scope("soft_cross"):
# 求平均交叉熵损失
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))
# 4.梯度下降求损失
with tf.variable_scope("optimizer"):
# 0.1是学习率,minimize表示求最小损失
train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)
# 5.计算准确率,每一个样本对应每个特征值都有一个概率,tf.argmax(y_true, 1), tf.argmax(y_predict, 1)返回的是分别是真实值和预测值的正确的下标,equal判断两个下标是否一致,一样,则这个样本被标为1
with tf.variable_scope("acc"):
equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
# equal_list None个样本 [1, 0, 1, 1, 0, 0.....]
accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
# 定义初始化变量op
init_op = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
# 初始化变量
sess.run(init_op)
for i in range(2000):
# 取出真实存在的特征值和目标值,50表示50个样本作为一个批次
mnist_x, mnist_y = mnist.train.next_batch(50)
# 运行训练op
sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})
# feed_dict这里的参数是必须,但是没有实际意义
print("训练第{}步,准确率:{}".format(i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))
if __name__ == "__main__":
con_vfc()