CS224dのTensorflow Tutorialを読んでみる

Tensoflowの公式のtutorialは眺めたことはあるが, 今一度確認のため,
CS224dのTensorflow tutorialを読んでみる.

f:id:yusuke_ujitoko:20170510232436p:plain

このメモは単なる写経です.
CS224dが気になる人は上のリンクを直接たどって見てみると良いと思います.

Tensorflowはnumpyと文法がそっくり.

例えば以下は同じ処理をTensorflowとnumpyで記述したもの.

import numpy as np

a = np.zeros((2,2))
b = np.ones((2,2))

print(np.sum(b, axis=1))
print(a.shape)

print(np.reshape(a, (1,4)))
import tensorflow as tf
tf.InteractiveSession()

a = tf.zeros((2,2))
b = tf.ones((2,2))

tf.reduce_sum(b, reduction_indices=1).eval()

a.get_shape()

tf.reshape(a, (1, 4)).eval()

ただしTensorflowは,式を明示的に評価する必要がある.

a = np.zeros((2,2))
ta = tf.zeros((2,2))

print(a)
# [[ 0.  0.]
#  [ 0.  0.]]

print(ta)
# Tensor("zeros_2:0", shape=(2, 2), dtype=float32)

print(ta.eval())
# [[ 0.  0.]
#  [ 0.  0.]]

Session Object

“A Session object encapsulates the environment in which Tensor objects are evaluated”

a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
with tf.Session() as sess:
        print(sess.run(c))
        print(c.eval())

ただしtf.InteractiveSession()を使うと,jupyter上でデフォルトのsessionを保持してくれる.

Tensor Variables

Variablesは初期化しなければならない.

W1 = tf.ones((2,2))
W2 = tf.Variable(tf.zeros((2,2)), name="weights")

with tf.Session() as sess:
    print(sess.run(W1))
    sess.run(tf.global_variables_initializer())
    print(sess.run(W2))

Variableの更新

state = tf.Variable(0, name="counter")

new_value = tf.add(state, tf.constant(1)) # new_value = state + 1
update = tf.assign(state, new_value) # state = new_value

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(state))

    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

複数の変数を同時にfetchすることもできる

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

intermed = tf.add(input2, input3)
mul = tf.multiply(input1, intermed)

with tf.Session() as sess:
    result = sess.run([mul, intermed])
    print(result)

Inputting data

これまではtf.でTensorflow内で主導で変数を定義していた.
外部からデータをTensorflowに取り込むにはどうするか.

numpy arrayを取り込むとき

a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)

with tf.Session() as sess:
    print(sess.run(ta))
# [[ 0.  0.  0.]
#  [ 0.  0.  0.]
#  [ 0.  0.  0.]]

ただ,convert_to_tensorは便利だけど,スケールしない.
そのため実際にはtf.placeholderを使う.
tf.placeholderはdummy nodeであり,計算グラフにデータを入れるentry pointsを提供するもの.

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
# [array([ 14.], dtype=float32)]