[Pytorch]:PyTorch中张量乘法大全

在 PyTorch 中,有多种方法可以执行张量之间的乘法。这里列出了一些常见的乘法操作:

总结:

  • 逐元素乘法:*ortorch.mul()
  • 矩阵乘法@ortorch.mm()ortorch.matmul()
  • 点积torch.Tensor.dot()
  • 批量矩阵乘法torch.bmm()torch.matmul()
  • 矩阵与向量相乘torch.mv(X, w0)
  1. 逐元素乘法(Element-wise multiplication):*ortorch.mul()()`对应位置的元素相乘,输入张量形状必须相同或可广播

    import torch
    
    A = torch.tensor([[1, 2], [3, 4]])
    B = torch.tensor([[2, 3], [4, 5]])
    
    result = A * B
    print(result)
    

    输出:

    tensor([[ 2,  6],
            [12, 20]])
    
  2. 矩阵乘法@ortorch.mm()ortorch.matmul()两个矩阵相乘,第一个矩阵的列数必须等于第二个矩阵的行数。

    import torch
    
    A = torch.tensor([[1, 2], [3, 4]])
    B = torch.tensor([[2, 3], [4, 5]])
    
    result = torch.matmul(A, B)
    print(result)
    

    输出:

    tensor([[10, 13],
            [22, 29]])
    

    或者使用 @ 运算符执行矩阵乘法:

    result = A @ B
    print(result)
    
  3. 点积(Dot product):torch.Tensor.dot()两个一维张量的点积。

    import torch
    
    A = torch.tensor([1, 2, 3])
    B = torch.tensor([4, 5, 6])
    
    result = torch.dot(A, B)
    print(result)
    

    输出:

    tensor(32)
    
  4. 批量矩阵乘法:对于具有更高维度的张量(点积),可以使用 torch.bmm()torch.matmul() 进行批量矩阵乘法。

    import torch
    
    A = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
    B = torch.tensor([[[2, 3], [4, 5]], [[6, 7], [8, 9]]])
    
    result = torch.bmm(A, B)
    print(result)
    

    输出:

    tensor([[[ 10,  13],
             [ 22,  29]],
    
            [[ 76,  91],
             [112, 133]]])
    

​ 两个输入张量的 batch_size 必须相同。此外,第一个输入张量的 num_columns 必须与第二个输入张量的 num_rows 相同。换句话说,输入张量的形状应为 (batch_size, num_rows_A, num_columns_A)(batch_size, num_columns_A, num_columns_B)

  1. 矩阵与向量相乘torch.mv(X, w0)第一个参数是矩阵,第二个参数只能是一维向量,等价于X乘以w0的转置
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值