TensorFlowを使ってみる 1
ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装
この本を読み終わったので機械学習を実験してみようと思います。
ライブラリはGoogleが公開しているTensorFlowを使います
日本のPFI社が開発したChanierあたりも気になっているのでそのうち触ってみたいです
TensorFlowのインストール
PythonをAnacondaでインストールしているので以下のようにインストール
$ conda create -n tensorflow python=3.5
その次に環境を切り替えます
$ source activate tensorflow
ここで、私の環境ではシェルごと落ちる問題が発生しました。
調べると
pyenvとanacondaを共存させる時のactivate衝突問題の回避策3種類 - Qiita
pyenvのactivateと衝突しているらしいので、
export PATH="$PYENV_ROOT/versions/anaconda3-2.4.0/bin/:$PATH"
をshellの設定ファイルに追記しておきます 「eval "$(pyenv init -)" 」より後に記述
プロンプトが切り替わったら以下を実行
※CPUでしか使わない人は実行するらしい
(tensorflow)/Users/sode% conda install -c conda-forge tensorflow
TensorFlowを使った簡単な計算
このサイトに載ってる簡単な計算が動くか試しておきました。
Graph
import tensorflow as tf matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.], [2.]]) product = tf.matmul(matrix1, matrix2) sess = tf.Session() result = sess.run(product) print(result) sess.close()
このサイトの説明によると、TensorFlowはNodeとedgeで構成されていて、それをGraphと呼んでいる
Graphの計算はSessionが管理している。
このコード例だとmatrix1とmatrix2がedgeでmatmul(行列積)がNode、これらを組み合わせたproductがGraphって事ですね。
計算はSessionのrunメソッドで実施し、内部的には高度な最適化がされてそう。
Interactive Session
import tensorflow as tf sess = tf.InteractiveSession() x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0]) x.initializer.run() sub = tf.sub(x, a) print(sub.eval()) sess.close()
続いての例はtensorflowのeval使ってインタラクティブに(いちいちSession.runせずに)計算させたい時に使うっぽい。
Variables
import tensorflow as tf state = tf.Variable(0, name="counter") one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(sess.run(state)) for _ in range(3): sess.run(update) print(sess.run(state))
Variableは変数。assignもNodeの1種でSessionのrunで計算するまで評価されない。updateを評価(run)する際にassignとaddが走りstateが更新される。
Fetches
input1 = tf.constant([3.0]) input2 = tf.constant([2.0]) input3 = tf.constant([5.0]) intermed = tf.add(input2, input3) mul = tf.mul(input1, intermed) with tf.Session() as sess: result = sess.run([mul, intermed]) print(result)
Sessionのrunは同時に複数のGraphを渡し、同時に計算する事が可能
Feeds
import tensorflow as tf input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.mul(input1, input2) with tf.Session() as sess: print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
GraphのEdgeは型だけ用意しておいて評価時(run)に実体を渡してもいいよという事