书中第三章初看可能会有点懵,需要将计算图、张量结合起来看。
计算图
TensorFlow中的运算会通过计算图的形式表述。
以下为TensorFlow中两个向量相加的代码。
import tensorflow as tf
a = tf.constant([1.0,2.0],name="a")#tf.constant是一个计算,结果为一个张量,保存在变量a中
b = tf.constant([2.0,3.0],name="b")
result = a + b

TensorFlow会自动生成一个默认的计算图,如果没有特殊指定,运算会自动加入到这个计算图中。
张量
张量即Tensor,是TensorFlow中管理数据的形式。
- 零阶张量表示标量(scalar)也就是一个数或字符串;
- 一阶张量称为向量,可以理解为一维数组;
- n阶张量可以理解为n维数组。
在前面计算图的例子中:
print(result)
Tensor("add:0", shape=(2,), dtype=int32)
可以看到TensorFlow中的计算结果并不是一个具体的数值,而是以张量的结构保存下来,张量包含了三个属性:名字、维度和类型。
add:0表示result这个张量是计算节点add输出的第一个结果。
shape=(2,)表示这个张量是一个一阶张量。
dtype为张量的类型,每个张量只有唯一的类型,不同类型的张量不能够进行运算:
>>> a = tf.constant([1,2],name="a")
>>> b = tf.constant([1.0,2.0],name="b")
>>> result = a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_op
s.py", line 885, in binary_op_wrapper
y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y")
File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\o
ps.py", line 836, in convert_to_tensor
as_ref=False)
File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\o
ps.py", line 926, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\o
ps.py", line 774, in _TensorTensorConversionFunction
(dtype.name, t.dtype.name, str(t)))
ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float3
2: 'Tensor("b_1:0", shape=(2,), dtype=float32)'
这个运算中,因为b中数字带有小数点,Python会将之自动识别成float,而a中变量会被识别成int,所以两者类型不同,相加时会出现报错,为了避免发生这种错误,可以在定义张量时指定张量的类型。
>>> a = tf.constant([1,2],name="a",dtype=tf.float32)
>>> b = tf.constant([1.0,2.0],name="b")
>>> result = a + b
>>> result
<tf.Tensor 'add_2:0' shape=(2,) dtype=float32>
会话
>>> sess = tf.Session()#创建会话
>>> sess.run(result)#运行result,获取result的取值
array([ 2., 4.], dtype=float32)
>>> sess.close()#关闭会话,释放资源
可以通过tf.Tensor.eval(session)函数来计算一个张量的取值,当指定了默认会话之后,可以直接通过tf.Tensor.eval()获取张量的值。
>>> sess = tf.Session()
>>> result.eval(session=sess)
array([ 2., 4.], dtype=float32)
>>> sess = tf.Session()
>>> with sess.as_default():#将sess设定为默认会话
... print(result.eval())
...
[ 2. 4.]
TensorFlow中提供了一种直接构建默认会话的函数:
>>> sess = tf.InteractiveSession()
>>> print(result.eval())
[ 2. 4.]
>>> sess.close()
网友评论