多层感知机MLP_MNIST手写输入集识别

取自于TensorFlow实战

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#定义tensor的CPU运算优先级
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
#导入书写数字输入级
mnist=input_data.read_data_sets('MNIST_data/',one_hot=True)
#定义交互式会话框
sess=tf.InteractiveSession()
#定义模型结构参数,输入、隐藏层节点数
in_units=784
h1_units=300
#定义权重、偏置
#w1截断正态分布
w1=tf.Variable(tf.truncated_normal([in_units,h1_units],stddev=0.1))
b1=tf.Variable(tf.zeros([h1_units]))
w2=tf.Variable(tf.zeros([h1_units,10]))
b2=tf.Variable(tf.zeros([10]))
#定义输入、标签、dropout层保留率占位符
x=tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder(tf.float32,[None,10])
keep_prob=tf.placeholder(tf.float32)
#定义隐藏层、dropout层,输出层
hidden1=tf.nn.relu(tf.matmul(x,w1)+b1)
hidden1_drop=tf.nn.dropout(hidden1,keep_prob)
y=tf.nn.softmax(tf.matmul(hidden1_drop,w2)+b2)

#定义损失函数为交叉熵
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#定义训练器
train=tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)
#初始化计算图
tf.global_variables_initializer().run()
#定义训练过程,minibatch大小为100,dropout保持率为0.75
for i in range(3000):
    batch_x,batch_y=mnist.train.next_batch(100)
    train.run({x:batch_x,y_:batch_y,keep_prob:0.75})
#定义预测正误判断模型,(模型最大值index,标签最大值index)是否相等
correcct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
#将预测正误判断模型bool型数据转换为float32,求平均为准确率
accuracy=tf.reduce_mean(tf.cast(correcct_prediction,tf.float32))
#使用eval计算训练好后的模型的正确率
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1}))

猜你喜欢

转载自blog.csdn.net/qq_41644087/article/details/80488028