Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

TensorFlowやってみた 使い方

以下を参考にした。blog.btrax.com

Hello World

import tensorflow as tf

hello = tf.constant('Hello, world!')
sess = tf.Session()
print sess.run(hello)

a = tf.constant(555)
b = tf.constant(666)

print sess.run(a+b)

基本的な使い方

  1. グラフ表現
  2. Sessionsの文脈内でのグラフの実行
  3. テンソルとしてのデータ表現
  4. 変数を用いた状態保持
  5. feedを用い任意のOperationにデータを渡したり受け取ったりする

OverView

TensorFlowは計算をグラフとして表現してプログラミングをする。
ノードはOps(Operations)を表す。
opは0個以上のテンソルを取り、計算をして、0個以上のテンソルを出す。
テンソルとは多次元の配列である。
例として画像のミニバッチを4次元配列[batch, height, width, channels]で表現できる(値は浮動小数点)

TensorFlowのグラフは計算を記述している。何を計算するにしてもグラフはSessionにおいて開始されなければならない。
Sessionはグラフのopsをデバイス上に置く、デバイスとはつまりCPUもしくはGPUである。そして、それらを実行するメソッドを提供する。
これらのメソッドPythonのnumpy ndarrayとして、そしてC,C++のtensorflow::Tensorインスタンスとして生成されるテンソル
を返す。

グラフの作成

Tensor Flowはデフォルトのグラフを持っている。
これにnodeとしてopを追加していく。

定数

定数opとして1×2行列を2つつくり、その積を計算する。

import tensorflow as tf

# 1 * 2 matrix
matrix1 = tf.constant([[3., 3.]])

# 2 * 1 matrix
matrix2 = tf.constant([[2.], [2.]])

product = tf.matmul(matrix1, matrix2)

sess = tf.Session()
result = sess.run(product)
print result

sess.close()

withを使うと自動的にcloseされて便利

import tensorflow as tf

# 1 * 2 matrix
matrix1 = tf.constant([[3., 3.]])

# 2 * 1 matrix
matrix2 = tf.constant([[2.], [2.]])

product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
 result = sess.run(product)
 print result

1個以上のGPUを持っているマシンでは指定できる。

with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)
    ...

変数

変数を作ってもsessionで実行するまでは作られない。

#coding:UTF-8

import tensorflow as tf

# 変数counter作成
state = tf.Variable(0, name="counter")

# 定数1をつくり
one = tf.constant(1)

# 状態に足して新しい値をつくる
new_value = tf.add(state, one)

# 変数counterに新しい値を設定する
update = tf.assign(state, new_value)

# 変数初期化
init_op = tf.initialize_all_variables()


with tf.Session() as sess:
    sess.run(init_op) # 初期化実行
    print sess.run(state) # 変数作成
    for _ in range(3):
        sess.run(update) # 更新
        print sess.run(state)

opの結果を使う(Fetchs)

以下のように、中間でつかったintermedの値も取ってこれる。

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

Feeds

実行時に値を与える。

#coding:UTF-8

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.]})