tensorflow构建手写数字图像识别---softmax算法

来源:互联网 发布:6city类似软件 编辑:程序博客网 时间:2024/06/02 02:15

tensorflow构建手写数字图像识别—softmax算法,摘自tensorflow中文社区

import input_dataimport tensorflow as tfmnist=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%

阅读全文
0 0
原创粉丝点击