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)
相关推荐
春末的南方城市4 分钟前
开放指令编辑创新突破!小米开源 Lego-Edit 登顶 SOTA:用强化学习为 MLLM 编辑开辟全新赛道!
人工智能·深度学习·机器学习·计算机视觉·aigc
37手游后端团队10 分钟前
Claude Code Review:让AI审核更懂你的代码
人工智能·后端·ai编程
源代码杀手42 分钟前
深入解析 Spec Kit 工作流:基于 GitHub 的 Spec-Driven Development 实践
人工智能·github
szxinmai主板定制专家2 小时前
基于 ZYNQ ARM+FPGA+AI YOLOV4 的电网悬垂绝缘子缺陷检测系统的研究
arm开发·人工智能·嵌入式硬件·yolo·fpga开发
聚客AI2 小时前
🌈提示工程已过时?上下文工程从理论到实践的完整路线图
人工智能·llm·agent
C嘎嘎嵌入式开发2 小时前
(二) 机器学习之卷积神经网络
人工智能·机器学习·cnn
文心快码BaiduComate2 小时前
开工不累,双强护航:文心快码接入 DeepSeek-V3.2-Exp和 GLM-4.6,助你节后高效Coding
前端·人工智能·后端
AI小云2 小时前
【Python与AI基础】Python编程基础:函数与参数
人工智能·python
white-persist3 小时前
MCP协议深度解析:AI时代的通用连接器
网络·人工智能·windows·爬虫·python·自动化