note from dataguru Tensorflow神经网络框架-12周
In [14]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data",one_hot=True) #或者在当前目录下面/MNIST_data/*.gz
batch_size = 100
n_batch = 500 #mnist.train.num_examples
x = tf.placeholder(tf.float32,[None,784]) #None是行数
y = tf.placeholder(tf.float32,[None,10]) #None是行数
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
loss = tf.reduce_mean(tf.square(y-prediction))
train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
print("n_batch : " + str(n_batch))
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
Output:
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
n_batch : 500
Iter 0,Testing Accuracy 0.8178
Iter 1,Testing Accuracy 0.8663
Iter 2,Testing Accuracy 0.8793
Iter 3,Testing Accuracy 0.8859
Iter 4,Testing Accuracy 0.8918
Iter 5,Testing Accuracy 0.8955
Iter 6,Testing Accuracy 0.8988
Iter 7,Testing Accuracy 0.8993
Iter 8,Testing Accuracy 0.9033
Iter 9,Testing Accuracy 0.9029
Iter 10,Testing Accuracy 0.9048
Iter 11,Testing Accuracy 0.9064
Iter 12,Testing Accuracy 0.9069
Iter 13,Testing Accuracy 0.9076
Iter 14,Testing Accuracy 0.9086
Iter 15,Testing Accuracy 0.9098
Iter 16,Testing Accuracy 0.9104
Iter 17,Testing Accuracy 0.9115
Iter 18,Testing Accuracy 0.9127
Iter 19,Testing Accuracy 0.9124
Iter 20,Testing Accuracy 0.9136