TensorFlow Introductionを読みながら調べたことを書き残しておきます。
Introductionに書かれているコードを全て繋ぎあわせると、以下のようになります。
import tensorflow as tf
import numpy as np
# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
# Fit the line.
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
# Learns best fit is W: [0.1], b: [0.3]
Broadcasting operation
y = W * x_data + b
print(type(W)) # <class 'tensorflow.python.ops.variables.Variable'>
print(type(b)) # <class 'tensorflow.python.ops.variables.Variable'>
print(type(x_data)) # <class 'numpy.ndarray'>
print(type(y)) # <class 'tensorflow.python.framework.ops.Tensor'>
ここではtf.Variableとnumpy.ndarrayを掛けており、ギョッとするのですが、Tensorflowはnumpy-styleのブロードキャストをサポートするようです。詳しくはStackoverflowとGlossaryを見るとよいです。
Convert numpy to tensor
tf.Variableとtf.constantにはnumpy.ndarrayオブジェクトを直接渡すことができます。
import tensorflow as tf
import numpy as np
a = tf.Variable(np.arange(10))
c = (np.zeros(10))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(a)) # [0 1 2 3 4 5 6 7 8 9]
print(sess.run(c)) # [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Quoraにて、TensorFlow team at Googleの方が
Yes, the TensorFlow API is designed to make it easy to convert data to and from NumPy arrays:
と述べています。
Convert tensor to numpy
tensorからnumpyに変換するには、Session.run か eval でOKです。
import tensorflow as tf
import numpy as np
x = tf.zeros([10])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(type(sess.run(x)))
print(type(x.eval()))
なお、APIドキュメントを見る限り、x.eval() は sess.run(x) のシンタックスシュガーだと思ってよさそうです。