Skip to content

Instantly share code, notes, and snippets.

@BIGBALLON
Last active February 5, 2018 05:57
Show Gist options
  • Save BIGBALLON/5821d9414f7c5e15edb2e1ce12a45cf4 to your computer and use it in GitHub Desktop.
Save BIGBALLON/5821d9414f7c5e15edb2e1ce12a45cf4 to your computer and use it in GitHub Desktop.
example for tensorflow
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
def main(_):
mnist = input_data.read_data_sets("./data", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.truncated_normal(shape=[784, 10], stddev=0.1))
b = tf.Variable(tf.constant(0.1, shape=[10]))
y = tf.matmul(x, W) + b
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Attach summaries to loss & accuracy
tf.summary.scalar('loss', cross_entropy)
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# create a writer to save logs
writer = tf.summary.FileWriter('./tb_logs',sess.graph)
for it in range(5000):
batch_xs, batch_ys = mnist.train.next_batch(128)
# run merged op in session
_, loss, summary = sess.run([train_step, cross_entropy, merged], feed_dict={x: batch_xs, y_: batch_ys})
print("iteration: {}, loss: {}".format(it, loss))
writer.add_summary(summary, it)
final_test = sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels})
print("final test acc: %.2f"%final_test)
if __name__ == '__main__':
tf.app.run(main=main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment