前言:卷积神经网络mnis数字识别问题
第一步:源码
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.saved_model.model_utils.mode_keys import is_train
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
tf.app.flags.DEFINE_integer("is_train", 1, "指定模型是训练还是预测")
FLAGS = tf.app.flags.FLAGS
# 定义一个初始化权重的函数,传入参数的形状
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():
"""
自定义卷积模型
:return:
"""
# 1.建立数据的占位符 x [None, 784] y_true [None, 10]
with tf.variable_scope("data"):
x = tf.placeholder(tf.float32, [None, 784])
y_true = tf.placeholder(tf.int32, [None, 10])
# 2.一卷积层,卷积,激活,池化
with tf.variable_scope("cov1"):
# 随机初始化权重,初始化偏置
w_conv1 = weight_variables([5, 5, 1, 32])
b_conv1 = bias_variables([32])
# 对x进行形状的改变[None, 784] [None, 28, 28, 1],因为改变的行数不知道
# 故行数那里填-1,这里改变形状采用的是动态改变形状
x_reshape = tf.reshape(x, [-1, 28, 28, 1])
# 步长为1,这样写表示上下左右移动的步长都是1,再进行激活
# [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,步长为2,[None, 28, 28, 32]-------->[None, 14, 14, 32]
x_pool1 = tf.nn.max_pool(x_relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 3.二卷积层,卷积,激活,池化
with tf.variable_scope("cov2"):
# 随机初始化权重,初始化偏置
w_conv2 = weight_variables([5, 5, 32, 64])
b_conv2 = bias_variables([64])
# 64个过滤器,步长为1,padding = "SAME" , bias=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,步长为2,[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")
# 4.全连接层,[None, 7, 7, 64]----->[None, 7*7*64] * [7*7*64, 10] +[10] = [None, 10]
with tf.variable_scope("full_connected"):
# 1.随机初始化权重和偏置
w_fc = weight_variables([7*7*64, 10])
b_fc = bias_variables([10])
# 2.进行矩阵运算,得出每个样本的10个结果,修改形状
x_reshape1 = tf.reshape(x_pool2, [-1, 7*7*64])
y_predict = tf.matmul(x_reshape1, w_fc) + b_fc
return x, y_true, y_predict
def conv_fc():
# 1.获取真实数据
mnist = input_data.read_data_sets("./data", one_hot=True)
# 2.定义模型,得出输出
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"):
train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
# 5.计算准确率
with tf.variable_scope("accuracy"):
equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
# equal_list None个样本 [1, 1, 1, 0, ..............1]]
accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
# 定义一个初始化变量的op
init_op = tf.global_variables_initializer()
# 收集变量,单个数字值收集
tf.summary.scalar("losses", loss)
tf.summary.scalar("acc", accuracy)
# 定义一个合并变量的op
merged = tf.summary.merge_all()
# 定义一个保存模型的实例op
saver = tf.train.Saver()
# 开启会话运行
with tf.Session() as sess:
sess.run(init_op)
# 建立events文件,然后写入
fw = tf.summary.FileWriter("./tmp/summary/test", graph=sess.graph)
# 迭代步数去训练,更新参数预测
for i in range(100):
# 每一次给50个数据进行训练,取出真实存在的特征值和目标值
mnist_x, mnist_y = mnist.train.next_batch(50)
# 运行train_op训练
sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})
# 写入每步训练的值
summary = sess.run(merged, feed_dict={x: mnist_x, y_true: mnist_y})
# 添加到写入的文件当中
fw.add_summary(summary, i)
print("训练第%d步,准确率为:%f" % (i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))
saver.save(sess, "./tmp/summary/smodl/fc_model")
return None
if __name__ == "__main__":
conv_fc()
第二部:代码运行结果和可视化参数变化情况