import tensorflow as tf
import numpy as np
import input_data
"""
构建neural network识别mnist数据集
"""
#加载mnist数据
mnist = input_data.read_data_sets('mnist',one_hot=True) #one_hot=True表示(0:1000000000)
#定义模型
def add_layer(inputs,in_size,out_size,activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size,out_size],mean=1,stddev=0))
biases = tf.Variable(tf.zeros([1,out_size])+0.25)
out1 = tf.matmul(inputs,Weights)+biases
if activation_function is None:
outputs = out1
else:
outputs = activation_function(out1)
return outputs
def show_accuracy(v_xs,v_ys):
global prediction
y_pre = sess.run(prediction,feed_dict={xs:v_xs}) #预测值
true_pre = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1)) #axis = 1判断正确和错误的比较
accuracy = tf.reduce_mean(tf.cast(true_pre,tf.float32)) #tf.cast将true_pre映射为float32类型
result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
return result
xs = tf.placeholder(tf.float32,[None,784]) #28*28=784,None表示样本
ys = tf.placeholder(tf.float32,[None,10]) #one_hot = True
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)
#定义交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
#梯度下降
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
init = tf.initialize_all_variables()#变量初始化
sess.run(init)
for i in range(1000):
batch_xs,batch_ys = mnist.train.next_batch(500) #按批训练数据
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
if i % 50:
print(show_accuracy(mnist.test.images,mnist.test.labels))#真实数据
结果:精度显著提高