変数はグラフの実行を通じて状態を保持します。次の例題は単純なカウンターとして作用する変数の例です。
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.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))
# 出力:
#
# 0
# 1
# 2
# 3
import tensorflow as tf
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)
# 出力:
#
# [21.0, 7.0]
TensorFlow はまた、グラフにおける任意の操作にテンソルを直接あてがうために feed(供給)機構を提供しています。
feed(供給)は操作 (OP) の出力を一時的にテンソル値で置き換えます。feed data(供給データ)は run() 呼び出しの引数として供給します。feed は run 呼び出しに対してのみ渡されて使用されます。最も一般的なユースケースでは特定の操作を “feed” 操作に指定することを伴います。tf.placeholder() を使用してそれらを作成します :
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.]}))
print (sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
# 出力:
#
# [ 14.]
# [array([ 14.], dtype=float32)]