【Pytorch】广播机制

【参考:The size of tensor a must match the size of tensor b (y) at non-singleton dimension z_点PY的博客-CSDN博客】

报错:The size of tensor a (x) must match the size of tensor b (y) at non-singleton dimension z

其广播机制遵循以下规则:

  • 每个张量至少具有一个维度;
  • 广播时,从尾部维度开始,满足尺寸大小相等其中一个为1其中一个不存在

【Pytorch】广播机制_第1张图片

维度对应
5 3 4 2
  3 1 1

怎样广播?
【参考:Pytorch中的广播机制(Broadcast)_cv_lhp的博客-CSDN博客】

以数组A和数组B的相加为例, 其余数学运算同理
核心:如果相加的两个数组的shape不同, 就会触发广播机制:
1)程序会自动执行操作使得A.shape==B.shape;
2)对应位置进行相加运算,结果的shape是:A.shape和B.shape对应位置的最大值
比如:
A.shape=(1,9,4),
B.shape=(15,1,4),
那么A+B的shape是(15,9,4)

你可能感兴趣的:(#,+,Pytorch,pytorch,python,深度学习)