Tensorflow之张量

计算模型

例子:

import tensorflow as tf

# tf.constant是一个计算,这个计算的结果为一个张量,保存在变量a中。
a = tf.constant([1.0,2.0], name="a")
b = tf.constant([2.0,3.0], name="b")
result = tf.add(a,b,name="add")
print(result)

输出结果:

Tensor("add:0", shape=(2,), dtype=float32)

从结果可以看出,一个张量中主要保存的了三个属性:名字(name)、维度(shape)和类型(type)

name

张量的命名形式:node:src_output
其中node为节点的名称,src_output表示当前张量来自节点的第几个输出。比如上面打印出来的“add:0"就说明result这个张量是计算节点”add“输出的第一个结果

shape

该属性描述了一个张量的维度信息,比如上面样例中shape=(2,)说明张量result是一个长度为2的一维数组。

type

每一个张量会有一个唯一的类型,运行时Tensorflow会对参与运算的所有张量进行类型的检查,当发现类型不匹配时会报错,比如下面这段程序:

import tensorflow as tf
a = tf.constant([1, 2], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")

报错:

ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("b:0", shape=(2,), dtype=float32)'

如果将一个加数指定成实数类型就不会出错了

a = tf.constant([1, 2], name="a", dtype=tf.float32)
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")

为了避免导致类型不匹配的问题,建议通过dtype来明确指定变量或常量的类型

数据模型

张量使用主要可以归结为两大类

对中间结果的引用

# 使用张量记录中间的结果
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = a + b

# 直接计算向量的和,这样可读性性会变差
result = tf.constant([1.0, 2.0], name="a") + tf.constant([2.0, 3.0], name="b")

获取计算图的结果

当计算图构造完成之后,张量可以用来获的计算结果,可以通过会话(Session)得到真实数字,代码如下

tf.Session().run(result)

你可能感兴趣的:(Tensorflow之张量)