Hello, Tensor World!
让我们来分析一下你刚才跑的 Hello World 的代码。代码如下:
import tensorflow as tf
# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')
with tf.Session() as sess:
# Run the tf.constant operation in the session
output = sess.run(hello_constant)
print(output)
Tensor
在 TensorFlow 中,数据不是以整数,浮点数或者字符串形式存在的。这些值被封装在一个叫做 tensor 的对象中。在 hello_constant = tf.constant('Hello World!')
代码中,hello_constant
是一个 0 维度的字符串 tensor,tensors 还有很多不同大小:
# A is a 0-dimensional int32 tensor
A = tf.constant(1234)
# B is a 1-dimensional int32 tensor
B = tf.constant([123,456,789])
# C is a 2-dimensional int32 tensor
C = tf.constant([ [123,456,789], [222,333,444] ])
tf.constant()
是你在这课中多个 TensorFlow 运算之一。tf.constant()
返回的 tensor 是一个常量 tensor,因为这个 tensor 的值不会变。
Session
TensorFlow 的 api 构建在 computational graph 的概念上,它是一种对数学运算过程进行可视化的一种方法。让我们把你刚才运行的 TensorFlow 的代码变成一个图:
如上图所示,一个 "TensorFlow Session" 是用来运行图的环境。这个 session 负责分配 GPU(s) 和/或 CPU(s) 包括远程计算机的运算。让我们看看怎么使用它:
with tf.Session() as sess:
output = sess.run(hello_constant)
这段代码已经从上一行创建了一个 tensor hello_constant
。下一行是在session里对 tensor 求值。
这段代码用 tf.Session
创建了一个sess
的 session 实例。 sess.run()
函数对 tensor 求值,并返回结果。