import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 1.利用数据,在训练的时候实时提供数据
# mnist手写数字数据在运行的时候实时提供占位符
tf.app.flags.DEFINE_integer("is_train",1,"指定是否训练模型,还是拿数据去预测")
FLAGS=tf.app.flags.FLAGS
def create_weight(shape):
return tf.Variable(initial_value=tf.random_normal(shape=shape))
def create_model(x):
"""
构建卷积神经网络
:return:
"""
# 1.第一个卷积大层
with tf.variable_scope("conv1"):
# 卷积层
# 将x[None,784]形状进行修改
input_x=tf.reshape(x,shape=[-1,28,28,1])
# 定义filter和偏置
conv1_weight=create_weight(shape=[5,5,1,32])
conv1_bias=create_weight(shape=[32])
conv1_x=tf.nn.conv2d(input=input_x,filter=conv1_weight,strides=[1,1,1,1],padding="SAME")+conv1_bias # 激活层
# 激活层
relu_x=tf.nn.relu(conv1_x)
# 池化层
pool_x=tf.nn.max_pool(value=relu_x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
# 2.第二个卷积大层
with tf.variable_scope("conv2"):
# 卷积层
# 定义filter和偏置
conv2_weight = create_weight(shape=[5, 5, 32, 64])
conv2_bias = create_weight(shape=[64])
conv2_x = tf.nn.conv2d(input=pool_x, filter=conv2_weight, strides=[1, 1, 1, 1],
padding="SAME") + conv2_bias
# 激活层
relu2_x = tf.nn.relu(conv2_x)
# 池化层
pool2_x = tf.nn.max_pool(value=relu2_x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 3.全连接层
with tf.variable_scope("full_connect"):
# [None,7,7,64]->[None,7*7*64]
# [None,7*7*64,10]=[None,10]
x_fc=tf.reshape(pool2_x,shape=[-1,7*7*64])
weight_fc=create_weight(shape=[7*7*64,10])
blas_fc=create_weight(shape=[10])
y_predict=tf.matmul(x_fc,weight_fc)+blas_fc
return y_predict
def full_connection():
"""
用全连接来对数字进行识别
特征值:[None,784]
目标值:one_hot编码[None,10]
:return:
"""
# 1.准备数据
mnist=input_data.read_data_sets("./temp",one_hot=True)
with tf.variable_scope("mnist_data"):
x=tf.placeholder(dtype=tf.float32,shape=(None,784))
y_true=tf.placeholder(dtype=tf.float32,shape=(None,10))
y_predict=create_model(x)
# 3.构造损失函数
with tf.variable_scope("softmax_crossentropy"):
error=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))
# 4.优化损失函数
with tf.variable_scope("optimizer"):
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)
# 5.准确率计算
with tf.variable_scope("accracy"):
equal_list=tf.equal(tf.arg_max(y_true,1),
tf.arg_max(y_predict,1))
accuracy=tf.reduce_mean(tf.cast(equal_list,tf.float32))
tf.summary.scalar("losses",error)
tf.summary.scalar("acc",accuracy)
# 初始化变量
init=tf.global_variables_initializer()
# 合并所有变量
merged=tf.summary.merge_all()
# 创建模型保存加载
# 开启回话
with tf.Session() as sess:
sess.run(init)
# 创建事件文件
# 拿真实值
# 创建一个event文件实例
file_writer=tf.summary.FileWriter("E:\python file",graph=sess.graph)
if FLAGS.is_train == 1:
for i in range(100):
mnist_x, mnist_y = mnist.train.next_batch(50)
sess.run(optimizer,feed_dict={x:mnist_x,y_true:mnist_y})
a,loss,accuracy_value=sess.run([optimizer,error,accuracy],feed_dict={x:mnist_x,y_true:mnist_y})
print("第%d次的训练,损失为%f,准确率为%f,"% (i+1,loss,accuracy_value))
# 运行合变量,写入事件文件
summery=sess.run(merged,feed_dict={x:mnist_x,y_true:mnist_y})
file_writer.add_summary(summery,i)
else:
for i in range(100):
# 每次拿一个样本测
mnist_x,mnist_y=mnist.test.next_batch(1)
print("第%d个样本的真实值为%d,模型预测结果为%d"%(i+1,tf.argmax(sess.run(y_true,feed_dict={x:mnist_x,y_true:mnist_y}),1),
tf.argmax(sess.run(y_predict, feed_dict={x: mnist_x, y_true:mnist_y}),1)))
return None
full_connection()