In [1]:
import tensorflow as tf
In [2]:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/tensorflow/alex/mnist/input_data', one_hot=True)
In [3]:
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='input')
W = tf.Variable(initial_value=tf.zeros([784, 10], dtype=tf.float32), name='weights', trainable=True)
b = tf.Variable(initial_value=tf.zeros([10]), dtype=tf.float32, name='bias', trainable=True)
out = tf.matmul(x, W) + b
y = tf.placeholder(tf.float32, [None, 10])
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=out))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
In [4]:
sess = tf.Session()
sess.run(tf.global_variables_initializer())
In [5]:
for _ in range(1000):
xs, ys = mnist.train.next_batch(100)
sess.run(optimizer, feed_dict={x: xs, y: ys})
In [6]:
# Graph
prediction = tf.argmax(out, 1)
target = tf.argmax(y, 1)
correct_prediction = tf.equal(prediction, target)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Execute
test_result = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print('Test accuracy: {0}'.format(test_result))