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)
相关推荐
试剂界的爱马仕9 分钟前
Anti-mouse PD-1 mAb (Clone RMP1-14) 与 Axitinib 小鼠实验使用方案整理汇总
大数据·人工智能·深度学习·学习
dreamread15 分钟前
2026带详细解读的八字排盘App怎么选:看解释层级、AI边界和复盘价值
人工智能·软件工具·传统文化
每天三杯咖啡20 分钟前
【无标题】
人工智能·技术选型·deepseek
nbtang202629 分钟前
AI Agent 入门(三):Tool Use 入门 —— Function Calling 原理与实战
人工智能·ai·agent
anOnion31 分钟前
Agentic 前端开发之 实时显示 AI Agent 终端输出
前端·javascript·人工智能
AI 大模型学习不踩坑33 分钟前
OpenClaw 完整教程:从安装到使用(官方脚本版)
java·人工智能·神经网络·机器学习·计算机视觉·自然语言处理·openclaw
不爱记笔记36 分钟前
ClaudeCode接入DeepSeek教程!防封号!
人工智能·ai·deepseek·claudecode
随风一样自由41 分钟前
【前端领域】2026最新前端领域全梳理(框架/工具/AI/跨端/底层标准/就业趋势)
前端·人工智能·前端框架
新知图书1 小时前
RAG之生成技术
人工智能·agent·ai agent·智能体·langgraph
漫步人生走在路上1 小时前
外贸GEO vs 传统SEO:区别有多大?
人工智能·搜索引擎·chatgpt·facebook·twitter