chooblarin’s blog

TensorFlow入門以前

August 16, 2016

  • #Machine Leaning
  • #TensorFlow

ずっと気になっていたTensorFlowを触ってみました. TensorFlow の情報は既に Web 上で大量に溢れかえっていてとてもありがたかったです. Qiita でのキーワード検索結果は執筆時点で 472 件です. 大いに参考にさせて頂きました.

ちなみに私は少し前から機械学習をこそこそと勉強しているアプリエンジニアです.

実験環境は下記.

  • Python: 3.5.1
  • TensorFlow: 0.10.0rc0

※ニューラルネットワークはでてきません

TensorFlow の基礎知識

TensorFlow は一連の計算をグラフで表現します. "Operation"と呼ばれるものがグラフのノードです. Operation は 0 個以上の計算対象を受け取って 0 個以上の計算結果を生成します. 計算結果と計算対象は,Tensor と呼ばれる多次元配列です (物理や数学でのテンソルと同義). Tensor はグラフのエッジに相当します. この Operation を複数つなぎ合わせて所望の結果を得るようです. このようにグラフで表された計算を,実行するには,Session オブジェクトを利用します. また,学習の状態を保存するために,Variable を使うようです.

↓ ドキュメントをパラパラっと見てイメージを掴むと良さそうです.

Introduction をやってみる

公式の GET STARTEDでは 一次関数 $y = Wx + b$ について,$W$ と $b$ を最小二乗法で求めるサンプルが公開されていました. (ちなみに $W$ は weight, $b$ は bias です.)

上述の基礎知識を思い出しつつコードを眺めると,やっていることが大体理解出来ました. (ここでさっぱりイメージが湧かない人は,おそらく機械学習に関する知識が不足していますのでどこかで補いましょう.)

Example

Example の多くがMNISTの手書き数字画像を用いたものになっています. 素晴らしい Example なのですがもう少し単純なもので試したい気もします. 今回はIris Data Setを使います. アルゴリズムは機械学習で最も単純な最近傍法を用います.

下記はこちらのサンプルコードを Iris 版に書きなおしたものです.

# -*- coding: utf-8 -*-

import random
import numpy as np
import tensorflow as tf
from sklearn import datasets

iris = datasets.load_iris()

n_sample = list(range(len(iris.data)))
random.seed(0)
random.shuffle(n_sample)

n_train = n_sample[:100]
n_test = n_sample[100:]

X_train = [iris.data[i] for i in n_train]
Y_train = [iris.target[i] for i in n_train]

X_test = [iris.data[i] for i in n_test]
Y_test = [iris.target[i] for i in n_test]

x_train = tf.placeholder("float", [None, 4])
x_test = tf.placeholder("float", [4])

distance = tf.reduce_sum(tf.abs(tf.add(x_train, tf.neg(x_test))), reduction_indices=1)
prediction = tf.arg_min(distance, 0)

accuracy = 0

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)

    for i in range(len(X_test)):
        nn_index = sess.run(prediction, feed_dict={x_train: X_train, x_test: X_test[i]})
        pred = Y_train[nn_index]
        cls = Y_test[i]
        print("Test", i, "Prediction:", pred, "True Class:", cls)

        if pred == cls:
            accuracy += 1./len(X_test)
    print("Done.")
    print("Accuracy:", accuracy)

実行結果

Test 0 Prediction: 0 True Class: 0
Test 1 Prediction: 1 True Class: 1
Test 2 Prediction: 2 True Class: 1
Test 3 Prediction: 2 True Class: 2
Test 4 Prediction: 1 True Class: 1
Test 5 Prediction: 1 True Class: 1
Test 6 Prediction: 1 True Class: 1
Test 7 Prediction: 0 True Class: 0
Test 8 Prediction: 0 True Class: 0
Test 9 Prediction: 2 True Class: 2
Test 10 Prediction: 2 True Class: 2
Test 11 Prediction: 0 True Class: 0
Test 12 Prediction: 0 True Class: 0
Test 13 Prediction: 2 True Class: 2
Test 14 Prediction: 2 True Class: 2
Test 15 Prediction: 1 True Class: 1
Test 16 Prediction: 1 True Class: 1
Test 17 Prediction: 2 True Class: 1
Test 18 Prediction: 0 True Class: 0
Test 19 Prediction: 2 True Class: 2
Test 20 Prediction: 1 True Class: 1
Test 21 Prediction: 1 True Class: 1
Test 22 Prediction: 0 True Class: 0
Test 23 Prediction: 2 True Class: 2
Test 24 Prediction: 0 True Class: 0
Test 25 Prediction: 0 True Class: 0
Test 26 Prediction: 1 True Class: 1
Test 27 Prediction: 2 True Class: 2
Test 28 Prediction: 1 True Class: 1
Test 29 Prediction: 0 True Class: 0
Test 30 Prediction: 0 True Class: 0
Test 31 Prediction: 1 True Class: 1
Test 32 Prediction: 0 True Class: 0
Test 33 Prediction: 1 True Class: 1
Test 34 Prediction: 0 True Class: 0
Test 35 Prediction: 2 True Class: 2
Test 36 Prediction: 2 True Class: 1
Test 37 Prediction: 0 True Class: 0
Test 38 Prediction: 2 True Class: 2
Test 39 Prediction: 1 True Class: 1
Test 40 Prediction: 1 True Class: 1
Test 41 Prediction: 2 True Class: 2
Test 42 Prediction: 1 True Class: 1
Test 43 Prediction: 2 True Class: 2
Test 44 Prediction: 2 True Class: 2
Test 45 Prediction: 2 True Class: 2
Test 46 Prediction: 1 True Class: 1
Test 47 Prediction: 0 True Class: 0
Test 48 Prediction: 2 True Class: 2
Test 49 Prediction: 1 True Class: 1
Done.
Accuracy: 0.94

今日はここまで.

参考