PyTorch广播机制

参考链接: PyTorch广播机制:Broadcasting semantics

总结:两个张量的shape从后往前逐个检查,要么对应维度相等,要么其中一个的维度上长度是1,或者其中一个的维度缺失,则在相应维度上扩充,使得和另一个张量的对应维度上的长度相等.否则广播失败,程序报错.

在这里插入图片描述
在这里插入图片描述

实验举例
在这里插入图片描述
在这里插入图片描述
实验代码展示:

(base) PS C:\Users\chenxuqi> conda activate ssd
(ssd) PS C:\Users\chenxuqi> python
Python 3.6.12 |Anaconda, Inc.| (default, Sep  9 2020, 00:29:25) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> x = torch.ones(1,3)
>>> y = torch.ones(3,1)
>>> (x+y).shape
torch.Size([3, 3])
>>>
>>> x = torch.ones(1,1)
>>> y = torch.ones(3,1)
>>> (x+y).shape
torch.Size([3, 1])
>>>
>>> x = torch.ones(1,1)
>>> y = torch.ones(1,3)
>>> (x+y).shape
torch.Size([1, 3])
>>>
>>> x = torch.ones(1,3,1,3)
>>> y = torch.ones(3,1,3,1)
>>> (x+y).shape
torch.Size([3, 3, 3, 3])
>>>
>>>

在这里插入图片描述
实验代码展示:

>>>
>>>
>>> x = torch.ones(2,3,1,3)
>>> y = torch.ones(3,1,3,1)
>>> (x+y).shape
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 0
>>>
>>> x = torch.ones(5,6)
>>> y = torch.ones(4,6)
>>> (x+y).shape
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: The size of tensor a (5) must match the size of tensor b (4) at non-singleton dimension 0
>>>
>>> x = torch.ones(2)
>>> y = torch.ones(3)
>>> (x+y).shape
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 0
>>>
>>>

在这里插入图片描述
实验代码展示:

>>>
>>> x = torch.ones(2,3,5,7)
>>> y = torch.ones(3,5,7)
>>> (x+y).shape
torch.Size([2, 3, 5, 7])
>>> x = torch.ones(2,1,4,1,6,1)
>>> y = torch.ones(3,6,7)
>>> (x+y).shape
torch.Size([2, 1, 4, 3, 6, 7])
>>>
>>> x = torch.ones(2,1,4,1,6,1)
>>> y = torch.ones(3,1,7)
>>> (x+y).shape
torch.Size([2, 1, 4, 3, 6, 7])
>>>
>>>

上一篇: NumPy广播机制

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值