torch.bmm()函数解读

函数作用
计算两个tensor的矩阵乘法,torch.bmm(a,b),tensor a 的size为(b,h,w),tensor b的size为(b,w,h),注意两个tensor的维度必须为3.
代码示例

>>> c=torch.randn((2,5))
>>> print(c)
tensor([[ 1.0559, -0.3533,  0.5194,  0.9526, -0.2483],
        [-0.1293,  0.4809, -0.5268, -0.3673,  0.0666]])
>>> d=torch.reshape(c,(5,2))
>>> print(d)
tensor([[ 1.0559, -0.3533],
        [ 0.5194,  0.9526],
        [-0.2483, -0.1293],
        [ 0.4809, -0.5268],
        [-0.3673,  0.0666]])
>>> e=torch.bmm(c,d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Dimension out of range (expected to be in range of [-2, 1], but got 2)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

当tensor维度为2时会报错!

>>> ccc=torch.randn((1,2,2,5))
>>> ddd=torch.randn((1,2,5,2))
>>> e=torch.bmm(ccc,ddd)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: invalid argument 1: expected 3D tensor, got 4D at /opt/conda/conda-bld/pytorch_1535490206202/work/aten/src/TH/generic/THTensorMath.cpp:2304

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

维度为4时也会报错!

>>> cc=torch.randn((2,2,5))
>>>print(cc)
tensor([[[ 1.4873, -0.7482, -0.6734, -0.9682,  1.2869],
         [ 0.0550, -0.4461, -0.1102, -0.0797, -0.8349]],
         [[-0.6872,  1.1920, -0.9732,  0.4580,  0.7901],
         [ 0.3035,  0.2022,  0.8815,  0.9982, -1.1892]]])
>>>dd=torch.reshape(cc,(2,5,2))
>>> print(dd)
tensor([[[ 1.4873, -0.7482],
         [-0.6734, -0.9682],
         [ 1.2869,  0.0550],
         [-0.4461, -0.1102],
         [-0.0797, -0.8349]],
         [[-0.6872,  1.1920],
         [-0.9732,  0.4580],
         [ 0.7901,  0.3035],
         [ 0.2022,  0.8815],
         [ 0.9982, -1.1892]]])
>>>e=torch.bmm(cc,dd)
>>> print(e)
tensor([[[ 2.1787, -1.3931],
         [ 0.3425,  1.0906]],
         [[-0.5754, -1.1045],
         [-0.6941,  3.0161]]])
 >>> e.size()
torch.Size([2, 2, 2])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

正确!

                                </div>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值