TensorFlow MNIST 入门 代码
其实就是按照TensorFlow中文教程的内容一步步跟着敲的代码。
不过在运行代码的时候遇到代码中加载不到MNIST数据资源,似乎是被墙了((⊙﹏⊙)b)
于是自己手动下载了数据包,放到 MNIST_data/ 文件夹下,代码就能正常运转了。
资源链接如下:
http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
完整版代码如下:
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) w = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10]))+0.1 x = tf.placeholder(tf.float32,[None,784]) y_ = tf.placeholder(tf.float32,[None,10]) y = tf.nn.softmax(tf.matmul(x,w)+b) cross_entropy = -tf.reduce_sum(y_*tf.log(y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) for i in range(800): batch_xs,batch_ys=mnist.train.next_batch(100) sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys}) if i % 50 ==0: 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}))