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)
相关推荐
attitude.x24 分钟前
GEO优化供应商:AI搜索时代的“答案”构建与移山科技的引领,2025高性价比实战指南
人工智能·科技
井云AI1 小时前
井云智能体封装小程序:独立部署多开版 | 自定义LOGO/域名,打造专属AI智能体平台
人工智能·后端·小程序·前端框架·coze智能体·智能体网站·智能体小程序
张较瘦_1 小时前
[论文阅读] 人工智能 + 软件工程 | 技术债务管理新范式:五步法工作坊与行动研究实践
人工智能·软件工程
杨杨杨大侠1 小时前
Spring AI 系列(一):Spring AI 基础概念与架构入门
人工智能·spring·架构
nenchoumi31192 小时前
手持 Mid360 + RealSense 相机 + Jetson Orin 一体平台
人工智能·目标检测·计算机视觉·机器人·ros
大力财经3 小时前
百度Q2财报:总营收327亿 AI新业务收入首次超100亿
人工智能·百度
OAFD.8 小时前
机器学习之线性回归:原理、实现与实践
人工智能·机器学习·线性回归
云手机掌柜10 小时前
亚矩阵云手机:亚马逊第三方店铺多账号安全合规运营的核心技术支撑
安全·智能手机·矩阵·手机
SHIPKING39310 小时前
【机器学习&深度学习】LMDeploy的分布式推理实现
人工智能·深度学习
mit6.82411 小时前
[RestGPT] docs | RestBench评估 | 配置与环境
人工智能·python