您的位置:首页 > 编程语言

tensorflow下对MNIST数据集进行识别的程序代码

2017-05-06 14:02 501 查看
# 下载mnist数据集:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 引入tensorflow:
import tensorflow as tf

x = tf.placeholder(tf.float32, [None, 784])
# None意味着可以是任意长度的维度

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# 实现模型
y = tf.nn.softmax(tf.matmul(x, W) + b)

# 定义cost/loss,用cross_entropy
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
# 注:tensorflow源码中用的是tf.nn.softmax_cross_entropy_with_logits,目的是保持数值稳定

# 开始训练
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 启动模型,用InteractiveSession
sess = tf.InteractiveSession()

# 初始化变量
tf.global_variables_initializer().run()

# 运行 train_step 1000次
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 注:feed进去的数据,代替placeholder

# 评价模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


运行结果:

0.9172
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐