#训练之后可以识别图片,当错误出现五次,识别结束,用来学习MNIST神经网络识别数字图片
import tensorflow as tf
import numpy as npfrom tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
train_num = 2000 #训练次数
hidden_node = 784 #输入节点
ouput_node=10 #输出节点
mnist=input_data.read_data_sets('/tmp/data/',one_hot=True)
input_x=tf.placeholder(dtype=tf.float32)
input_y=tf.placeholder(dtype=tf.float32)
w=tf.Variable(tf.zeros([hidden_node,ouput_node]))
b=tf.Variable(tf.zeros([ouput_node]))
y_predict=tf.nn.softmax(tf.matmul(input_x,w)+b)
cross_entropy=-tf.reduce_sum(tf.log(y_predict)*input_y)
label=tf.argmax(input_y,1)
predict_label = tf.argmax(y_predict,1)
correct_prediction = tf.equal(label, predict_label)
tran_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
sess=tf.Session()
sess.run(tf.global_variables_initializer())
for _ in range(train_num):
batch_x, batch_y=mnist.train.next_batch(100)
sess.run(tran_step, feed_dict={input_x:batch_x,input_y:batch_y})
correct_num=0
wrong_num=0
for _ in range(100):
batch_x, batch_y = mnist.train.next_batch(1)
isCorrect = sess.run(correct_prediction, feed_dict={input_x: batch_x, input_y: batch_y})
if ( isCorrect):
correct_num+=1
else:
wrong_num +=1
if (wrong_num>5):
break
print('label ,predict_label', sess.run(label, feed_dict={input_x: batch_x, input_y: batch_y}), sess.run(predict_label, feed_dict={input_x: batch_x, input_y: batch_y}))
image = np.reshape(batch_x, [28, -1])
plt.imshow(image, cmap=plt.get_cmap('gray_r'))
plt.show()
print('correct, wrong', correct_num,wrong_num)