Tensorflow下的Mnist手写数字识别

本文介绍如何使用TensorFlow和MNIST数据集进行简单的手写数字识别。通过下载并预处理MNIST数据,利用TensorFlow构建了一个基本的神经网络模型,实现了对MNIST数据集的手写数字分类,并讨论了在实现过程中可能遇到的常见错误及其解决方案。

事先准备:在tensorflow官方文档网页上下载input_data.py,下载不了的话去网上查找,input_data.py用于下载和提取mnist数据

一、代码及注释

#下载mnist数据到当前路径下的MNIST_data文件夹中,同时进行提取
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
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)

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})
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})复制代码


二、报错及解决

错误1:No module named input_data

即没找到input_data.py,不能正常导入,有关python import的问题可详见上一份文档

解决方法:

(1)将下载的input_data.py和你代码文件(yourcode.py)放在同一路径下

(2)Tensorflow的安装目录下(/tensorflow/examples/tutorials/mnist)有该文件input_data.py,

于是可直接import,如下

from tensorflow.examples.tutorials.mnist import input_data

错误2:TypeError: only integer scalar arrays can be converted to a scalar index

解决方法:

可参考stackoverflow网站下的回答:

https://stackoverflow.com/questions/42128830/typeerror-only-integer-scalar-arrays-can-be-converted-to-a-scalar-index


如图,大意为导致该错误的原因是由于最新版的Numpy做了一些改动。根据图中方法,将下载到的input_data.py文件进行修改:在_read32函数定义最后增加[0]


转载于:https://juejin.im/post/5c33308fe51d45523070f638

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值