Pytorch: torch.matmul()执行矩阵的乘法

torch.matmul 是 PyTorch 中用于执行矩阵乘法的函数。它的设计目的是为了处理广泛的输入形状和操作,包括矩阵乘法、向量内积、批量矩阵乘法等。

语法

torch.matmul(input, other, out=None)

参数说明

  • input: 输入张量。
  • other: 第二个输入张量。
  • out (可选): 输出张量。

举例

  • 如果输入都是 1-D 张量,执行向量的内积。
  • 如果输入都是 2-D 张量,执行矩阵乘法。
  • 如果输入中至少有一个张量的维度大于 2,执行批量矩阵乘法。
  • 支持广播机制,根据 NumPy 广播规则进行自动广播。

矩阵乘法

import torch

# 创建两个矩阵
mat1 = torch.rand(2, 3)
mat2 = torch.rand(3, 4)

# 执行矩阵乘法
result_matmul = torch.matmul(mat1, mat2)

print(result_matmul.shape)  # 输出: torch.Size([2, 4])

批量矩阵乘法

import torch

# 创建两个三维张量
mat1 = torch.rand(3, 2, 3)
mat2 = torch.rand(3, 3, 4)

# 执行批量矩阵乘法
result_matmul_batch = torch.matmul(mat1, mat2)

print(result_matmul_batch.shape)  # 输出: torch.Size([3, 2, 4])

向量的内积

import torch

# 创建两个向量
vec1 = torch.rand(3)
vec2 = torch.rand(3)

# 执行向量的内积
result_inner_product = torch.matmul(vec1, vec2)

print(result_inner_product)  # 输出: 一个标量值

总的来说,torch.matmul 是一个非常通用的函数,能够处理多种输入形状,包括矩阵乘法、向量内积、批量矩阵乘法等。根据输入的具体形状,它会自动选择适当的操作。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值