|
| 1 | +import tensorflow as tf |
| 2 | +import numpy as np |
| 3 | +import input_data |
| 4 | + |
| 5 | + |
| 6 | +def init_weights(shape): |
| 7 | + return tf.Variable(tf.random_normal(shape, stddev=0.01)) |
| 8 | + |
| 9 | + |
| 10 | +def model(X, w_h, w_o): |
| 11 | + h = tf.nn.sigmoid(tf.matmul(X, w_h)) |
| 12 | + return tf.matmul(h, w_o) |
| 13 | + |
| 14 | + |
| 15 | +mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) |
| 16 | +trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels |
| 17 | + |
| 18 | +X = tf.placeholder("float", [None, 784]) |
| 19 | +Y = tf.placeholder("float", [None, 10]) |
| 20 | + |
| 21 | +w_h = init_weights([784, 625]) |
| 22 | +w_o = init_weights([625, 10]) |
| 23 | + |
| 24 | +py_x = model(X, w_h, w_o) |
| 25 | + |
| 26 | +cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y)) |
| 27 | +train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) |
| 28 | +predict_op = tf.argmax(py_x, 1) |
| 29 | + |
| 30 | +sess = tf.Session() |
| 31 | +init = tf.initialize_all_variables() |
| 32 | +sess.run(init) |
| 33 | + |
| 34 | +for i in range(100): |
| 35 | + for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): |
| 36 | + sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]}) |
| 37 | + print i, np.mean(np.argmax(teY, axis=1) == |
| 38 | + sess.run(predict_op, feed_dict={X: teX, Y: teY})) |
0 commit comments