pytorch矩阵乘法

torch.matmul

torch.matmul是PyTorch中执行一般矩阵乘法的函数,它接受两个矩阵作为输入,并返回它们的乘积。它适用于任何两个矩阵,无论是密集矩阵还是稀疏矩阵。

python 复制代码
import torch  
  
# 创建两个 2x2 矩阵  
mat1 = torch.tensor([[1, 2], [3, 4]])  
mat2 = torch.tensor([[5, 6], [7, 8]])  
  
# 使用torch.matmul进行矩阵乘法  
result = torch.matmul(mat1, mat2)  
  
print(result)

torch.mm

torch.mm是PyTorch中用于密集矩阵乘法的函数。它接受两个密集矩阵作为输入,并返回它们的乘积。与torch.matmul相比,torch.mm在处理密集矩阵时具有更高的性能和更简单的语法。

python 复制代码
import torch  
  
# 创建两个 2x2 矩阵  
mat1 = torch.Tensor([[1, 2], [3, 4]])  
mat2 = torch.Tensor([[5, 6], [7, 8]])  
  
# 使用torch.mm进行矩阵乘法  
result = torch.mm(mat1, mat2)  
  
print(result)

torch.spmm

torch.spmm是PyTorch中用于稀疏矩阵乘法的函数。它接受两个稀疏矩阵作为输入,并返回它们的乘积。与torch.matmul和torch.mm相比,torch.spmm更适用于处理包含大量零值元素的矩阵,因为它可以有效地处理稀疏结构并减少计算量。

python 复制代码
import torch  
import torch.sparse_coo_tensor as coo_tensor  
  
# 创建两个稀疏矩阵  
row_0 = [0, 1, 2]  
col_0 = [0, 2, 1]  
value_0 = [1, 2, 3]  
sparse_mat1 = coo_tensor.from_sparse((torch.tensor(row_0), torch.tensor(col_0), torch.tensor(value_0)))  
  
row_1 = [0, 2, 3]  
col_1 = [1, 0, 2]  
value_1 = [4, 5, 6]  
sparse_mat2 = coo_tensor.from_sparse((torch.tensor(row_1), torch.tensor(col_1), torch.tensor(value_1)))  
  
# 使用torch.spmm进行矩阵乘法  
result = torch.spmm(sparse_mat1, sparse_mat2)  
  
print(result)
相关推荐
stephon_1001 小时前
Agent 接入 MCP 后上下文爆炸、工具选串?一种“按需激活“的工具加载方案(含实现)
人工智能·python·ai
TickDB1 小时前
统一行情 API 查 A 股、港股、美股和数字货币:code=0 不代表 symbol 一个没少
人工智能·python·websocket·mcp·行情数据 api
菜鸡爱玩4 小时前
线性代数矩阵相乘
线性代数·算法·矩阵
滴图服务-七七6 小时前
滴滴地图:精准定位赋能企业数字化转型
大数据·人工智能·地图服务·甲级测绘资质·商业授权
爱学习的程序媛6 小时前
2026上半年大模型全景技术解读:推理融合、Agent 爆发与多模态统一
人工智能·ai
A.说学逗唱的Coke8 小时前
【大模型专题】向量数据库深度解析:从原理到实战,构建企业级 AI 知识检索底座
数据库·人工智能
果丁智能8 小时前
智能锁赋能网约房民宿数字化管控:身份核验+远程授权,筑牢安全防线、降本增效
网络·数据库·人工智能·安全·智能家居
V搜xhliang02468 小时前
AI智能体的数据安全与合规实践
人工智能·学习·数据分析·自动化·ai编程
PPIO派欧云8 小时前
PPIO登上贵州新闻联播,深化AI算力生态建设
人工智能
hai3152475438 小时前
一种通过空间几何转换进行软件编程计算的方式与现有计算的对比
人工智能·深度学习·数学建模·硬件架构·几何学·图论·拓扑学