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,或者其中一个不存在