1、add函数
函数原型
tf.add(
x, y, name=None
)
函数说明
x和y两个张量进行元素级的相加。如果x和y的形状不一致,则会利用python的广播机制,扩展x或y的形状,使两个张量的形状相同,然后再进行相加。
函数使用
1、x和y的形状相同
>>> x = tf.ones((2, 2))
>>> x
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 1.],
[1., 1.]], dtype=float32)>
>>> y = tf.reshape(tf.range(4), (2, 2))
>>> y = tf.cast(y, dtype=x.dtype)
>>> y
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[0., 1.],
[2., 3.]], dtype=float32)>
>>> tf.add(x, y)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
2、x和y的形状不一致
>>> x = tf.ones((2, 2))
>>> x
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 1.],
[1., 1.]], dtype=float32)>
>>> y = tf.constant([1, 1], dtype=x.dtype)
>>> tf.add(x, y)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
[2., 2.]], dtype=float32)>
>>> y = tf.constant([[1], [1]], dtype=x.dtype)
>>> tf.add(x, y)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
[2., 2.]], dtype=float32)>
>>> y = tf.constant([1], dtype=x.dtype)
>>> tf.add(x, y)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
[2., 2.]], dtype=float32)>
2、subtract函数
函数原型
tf.subtract(
x, y, name=None
)
函数说明
张量x和张量y实现元素级的相减。如果x和y的形状不一样,也会使用python的广播机制。
函数使用
1、x和y形状一致
>>> x = tf.fill((2, 2), 3)
>>> x
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[3, 3],
[3, 3]])>
>>> y = tf.reshape(tf.range(4), (2, 2))
>>> y
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[0, 1],
[2, 3]])>
>>> tf.subtract(x, y)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[3, 2],
[1, 0]])>
2、x和y形状不一致
>>> x = tf.fill((2, 2), 3)
>>> x
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[3, 3],
[3, 3]])>
>>> y = tf.constant([[1, 1]])
>>> y
<tf.Tensor: shape=(1, 2), dtype=int32, numpy=array([[1, 1]])>
>>> tf.subtract(x, y)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[2, 2],
[2, 2]])>