ゲームAI備忘録

ゲームAIに使えそうな知識を備忘録として書き留める

人助けと思って何卒インストールをば! 詰碁/ アルコネ/ 五目並べ

TensorFlow - MNISTのチュートリアル(初心者向け)を試してみる.

TensorFlowのMNISTチュートリアル(初心者向け)を試してみました.
MNIST For ML Beginners

MNISTとは

環境

  • TensorFlow: version 0.6.0

実行

下記スクリプトをmnist_beginner.pyとして貼り付けて実行することで精度を確認できます.
データを拾ってきて加工する部分は,そのままチュートリアルスクリプトinput_data.pyを使っています.

# mnist_beginner.py
import tensorflow as tf
import os
if not os.path.exists("input_data.py"):
    os.system("curl https://raw.githubusercontent.com/tensorflow/tensorflow/0.6.0/tensorflow/examples/tutorials/mnist/input_data.py -o input_data.py")
import input_data

def main(args):
    mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
    with tf.Session() as sess:
        # Variables 
        x = tf.placeholder("float", shape=[None, 784])
        y_ = tf.placeholder("float", shape=[None, 10]) # y'
        # Predicted Class and Cost Function
        W = tf.Variable(tf.zeros([784, 10]))
        b = tf.Variable(tf.zeros([10]))
        sess.run(tf.initialize_all_variables())
        y = tf.nn.softmax(tf.matmul(x, W) + b) # y = W.T * x + b
        cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) # H = -{y' * log(y) + (1-y') * log(1-y)}
        # Train the Model
        optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
        for i in range(1000):
            batch = mnist.train.next_batch(50)
            optimizer.run(feed_dict={x: batch[0], y_: batch[1]})
        # Evaluate the Model
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
        print "Accuracy: %.3f" % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels})

if __name__ == "__main__":
    tf.app.run()

実行結果

$ python mnist_beginner.py 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7309  100  7309    0     0  62090      0 --:--:-- --:--:-- --:--:-- 62470
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting MNIST_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
can't determine number of CPU cores: assuming 4
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
can't determine number of CPU cores: assuming 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
Accuracy: 0.909