import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
minist=input_data.read_data_sets("D://MNIST_data",one_hot=True)
batch_size=100 #定义一个批次数量大小
nbatch=minist.train.num_examples//batch_size #计算多少个批次
#定义两个PlaceHolder
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
#创建一个简单的神经网络
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
prediction=tf.nn.softmax(tf.matmul(x,w)+b)
#softmax和交叉熵配合使用
loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
init=tf.global_variables_initializer()
#结果存在一个布尔型类表中
correctPrediction=tf.equal(tf.arg_max(y,1),tf.arg_max(prediction,1))
accuracy=tf.reduce_mean(tf.cast(correctPrediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(1000):
for batch in range(nbatch):
batch_xs,batchys=minist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batchys})
acc=sess.run(accuracy,feed_dict={x:minist.test.images,y:minist.test.labels})
print("迭代次数:"+str(epoch)+ " "+"测试准确率: "+str(acc))
QQ技术交流群:386476712
FR:徐海涛(QQ技术交流群:386476712)