TensorFlow 数学
得到输入很棒,但是现在你需要把它用起来。你将用每个人都懂的常用的数学运算,加、减、乘、除来处理 tensor。(还有更多的运算,你可以看文档)。
加法
x = tf.add(5, 2) # 7
从加法开始, tf.add()
完成的工作与你期望的一样。它把两个数字,两个 tensor,返回他们的和。
减法和乘法
这是减法和乘法的例子:
x = tf.subtract(10, 4) # 6
y = tf.multiply(2, 5) # 10
x
tensor 求值结果是 6
,因为 10 - 4 = 6
。y
tensor 求值结果是 10
,因为 2 * 5 = 10
。是不是很简单!
类型转换
为了让特定运算能运行,有时会对类型进行转换。例如,你尝试下列代码,会报错:
tf.subtract(tf.constant(2.0),tf.constant(1)) # Fails with ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32:
只是因为常量 1
是整数,但是常量 2.0
是浮点数 subtract
需要他们能相符。
在这种情况下,你可以让数据都是同一类型,或者强制转换一个值到另一个类型。这里,我们可以把 2.0
转换成整数再相减,这样就能得出正确的结果:
tf.subtract(tf.cast(tf.constant(2.0), tf.int32), tf.constant(1)) # 1