How does pytorch broadcasting work?(pytorch 广播是如何工作的?)
问题描述
torch.add(torch.ones(4,1), torch.randn(4))
产生一个尺寸为:torch.Size([4,4])
.
有人可以提供这背后的逻辑吗?
示例 2:
:
T
和 F
分别代表 True
和 False
并指示我们允许广播的维度(来源:
torch.add(torch.ones(4,1), torch.randn(4))
produces a Tensor with size: torch.Size([4,4])
.
Can someone provide a logic behind this?
PyTorch broadcasting
is based on numpy broadcasting semantics which can be understood by reading numpy broadcasting rules
or PyTorch broadcasting guide. Expounding the concept with an example would be intuitive to understand it better. So, please see the example below:
In [27]: t_rand
Out[27]: tensor([ 0.23451, 0.34562, 0.45673])
In [28]: t_ones
Out[28]:
tensor([[ 1.],
[ 1.],
[ 1.],
[ 1.]])
Now for torch.add(t_rand, t_ones)
, visualize it like:
# shape of (3,)
tensor([ 0.23451, 0.34562, 0.45673])
# (4, 1) | | | | | | | | | | | |
tensor([[ 1.],____+ | | | ____+ | | | ____+ | | |
[ 1.],______+ | | ______+ | | ______+ | |
[ 1.],________+ | ________+ | ________+ |
[ 1.]])_________+ __________+ __________+
which should give the output with tensor of shape (4,3)
as:
# shape of (4,3)
In [33]: torch.add(t_rand, t_ones)
Out[33]:
tensor([[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673]])
Also, note that we get exactly the same result even if we pass the arguments in a reverse order as compared to the previous one:
# shape of (4, 3)
In [34]: torch.add(t_ones, t_rand)
Out[34]:
tensor([[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673],
[ 1.23451, 1.34562, 1.45673]])
Anyway, I prefer the former way of understanding for more straightforward intuitiveness.
For pictorial understanding, I culled out more examples which are enumerated below:
Example-1:
Example-2:
:
T
and F
stand for True
and False
respectively and indicate along which dimensions we allow broadcasting (source: Theano).
Example-3:
Here are some shapes where the array b
is broadcasted appropriately to match the shape of the array a
.
这篇关于pytorch 广播是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pytorch 广播是如何工作的?


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01