Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pytorch 当张量大小不同时,为什么torch。张量减法效果很好?_Pytorch_Tensor_Torch - Fatal编程技术网

Pytorch 当张量大小不同时,为什么torch。张量减法效果很好?

Pytorch 当张量大小不同时,为什么torch。张量减法效果很好?,pytorch,tensor,torch,Pytorch,Tensor,Torch,这个例子将使它更容易理解。以下操作失败: A = tensor.torch([[1, 2, 3], [4, 5, 6]]) # shape : (2, 3) B = tensor.torch([[1, 2], [3, 4], [5, 6]]) # shape : (3, 2) print((A - B).shape) # RuntimeError: The size of tensor A (3) must match the size of tensor B (2) at non-sin

这个例子将使它更容易理解。以下操作失败:

A = tensor.torch([[1, 2, 3], [4, 5, 6]])   # shape : (2, 3)
B = tensor.torch([[1, 2], [3, 4], [5, 6]]) # shape : (3, 2)
print((A - B).shape)

# RuntimeError: The size of tensor A (3) must match the size of tensor B (2) at non-singleton dimension 1
# ==================================================================
A = tensor.torch([[1, 2], [3, 4], [5, 6]])   # shape : (3, 2)
B = tensor.torch([[1, 2], [3, 4],]) # shape : (2, 2)
print((A - B).shape)

# RuntimeError: The size of tensor A (3) must match the size of tensor B (2) at non-singleton dimension 0
但以下方法效果良好:

a = torch.ones(8).unsqueeze(0).unsqueeze(-1).expand(4, 8, 7) 
a_temp = a.unsqueeze(2)                            # shape : ( 4, 8, 1, 7 )
b_temp = torch.transpose(a_temp, 1, 2)             # shape : ( 4, 1, 8, 7 )
print(a_temp-b_temp)                               # shape : ( 4, 8, 8, 7 )
为什么后者有效,而前者无效?

结果形状是如何展开的/为什么展开的?

这一点可以通过下面的示例得到很好的解释。重要的部分是:

如果以下规则成立,则两个张量是“可广播的”:

  • 每个张量至少有一个维度
  • 从后面的标注开始迭代标注尺寸时,标注尺寸必须相等,其中一个为1,或者其中一个不存在
在您的情况下,(3,2)和(2,3)不能广播到公共形状(3!=2,两者都不等于1),但(4,8,1,7)、(4,1,8,7)和(4,8,8,7)是广播兼容的

这就是错误的基本状态:所有维度必须相等(“匹配”)或单态(即等于1)

播放形状时发生的情况基本上是一个匹配形状(扩展到[4,8,8,7]),然后像往常一样执行减法。扩展复制数据(以智能方式)以达到所需的形状