Last active
February 14, 2017 08:07
-
-
Save sodeyama/b60fe93967b07f6e820d32920f9c3ed6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import | |
from __future__ import division | |
from __future__ import print_function | |
import argparse | |
import sys | |
from tensorflow.examples.tutorials.mnist import input_data | |
import tensorflow as tf | |
from PIL import Image, ImageOps | |
import numpy as np | |
FLAGS = None | |
def predict(x, W1, b1, W2, b2): | |
a1 = tf.matmul(x, W1) + b1 | |
z1 = tf.sigmoid(a1) | |
a2 = tf.matmul(z1, W2) + b2 | |
y = tf.nn.softmax(a2) | |
return y | |
def get_result(sess, image_filenames, W1, b1, W2, b2): | |
data = [] | |
for filename in image_filenames: | |
img = np.array(Image.open(filename).convert("L")) | |
data.append(tf.constant((255 - img.flatten())/255, dtype=tf.float32)) | |
result = sess.run(predict(data, W1, b1, W2, b2)) | |
result = np.argmax(result, axis=1) | |
return result | |
def main(_): | |
# Import data | |
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) | |
# Create the model | |
std = 0.01 | |
x = tf.placeholder(tf.float32, [None, 784]) | |
W1 = tf.Variable(tf.random_normal([784, 100], stddev=std)) | |
b1 = tf.Variable(tf.zeros([100])) | |
W2 = tf.Variable(tf.random_normal([100, 10], stddev=std)) | |
b2 = tf.Variable(tf.zeros([10])) | |
y = predict(x, W1, b1, W2, b2) | |
y_ = tf.placeholder(tf.float32, [None, 10]) | |
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) | |
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) | |
sess = tf.InteractiveSession() | |
tf.global_variables_initializer().run() | |
# Train | |
for _ in range(10000): | |
batch_xs, batch_ys = mnist.train.next_batch(100) | |
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) | |
# Test | |
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})) | |
print(get_result(sess, ['1.png', '5.png', '7.png'], W1, b1, W2, b2)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data', | |
help='Directory for storing input data') | |
FLAGS, unparsed = parser.parse_known_args() | |
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment