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)
相关推荐
寻见9032 分钟前
救命!RAG检索总跑偏?bge-reranker-large彻底解决「找错文档」痛点
人工智能·langchain
TechFind15 分钟前
我用 OpenClaw 搭了一套运营 Agent,每天自动生产内容、分发、追踪数据——独立开发者的运营平替
人工智能·agent
小成C23 分钟前
Vibe Coding 时代,研发体系该怎么重新分工
人工智能·架构·全栈
37手游后端团队24 分钟前
全网最简单!从零开始,轻松把 openclaw 小龙虾装回家
人工智能·后端·openai
该用户已不存在24 分钟前
月薪2w养不起龙虾?试试OpenClaw+Ollama
人工智能·aigc·ai编程
Seeker25 分钟前
别盲目跟风“养龙虾”!OpenClaw爆火背后,这些致命安全风险必须警惕
人工智能·安全
golang学习记25 分钟前
Claude Code 官宣新 AI 功能!随时随地 AI 为你打工
人工智能·claude
IvanCodes1 小时前
OpenClaw保姆级安装教程:windows&ubuntu
人工智能
Serverless社区2 小时前
AgentRun实践指南:Agent 的宝藏工具—All-In-One Sandbox
人工智能
AngelPP2 小时前
拆解 OpenClaw 上下文引擎:一个 AI Agent 是如何管理"记忆"的
人工智能