tensorflow构建手写数字图像识别—softmax算法,摘自tensorflow中文社区
import input_data
import tensorflow as tf
mnist=input_data.read_data_sets("MNIST_data/", one_hot=True)
#添加x作为占位符
x=tf.placeholder("float", [None, 784])
#两个变量定义
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#预测算法定义
y=tf.nn.softmax(tf.matmul(x,W) + b)
#正确结果占位符
y_=tf.placeholder("float", [None,10])
#定义计算交叉熵公式
cross_entropy=-tf.reduce_sum(y_*tf.log(y))
#定义训练方式,梯度下降,目标让交叉熵减少
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#初始化变量
init=tf.initialize_all_variables()
sess=tf.Session()
sess.run(init
#循环训练1000次,每次取100个数据,run train_step方法,用batch_xs, batch_ys填充占位符
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
#tf.argmax(y,1):取出y数组中为1的序号,对比正确的计算准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
正确率91%