tensorflow add、subtarct函数

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]])>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不负韶华ღ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值