torch_bmm验算及代码测试

文章目录

  • [1. torch_bmm](#1. torch_bmm)
  • [2. pytorch源码](#2. pytorch源码)

1. torch_bmm

torch.bmm的作用是基于batch_size的矩阵乘法,torch.bmm的作用是对应batch位置的矩阵相乘,比如,

  • mat1的第1个位置和mat2的第1个位置进行矩阵相乘得到mat3的第1个位置
  • mat1的第2个位置和mat2的第2个位置进行矩阵相乘得到mat3的第2个位置

2. pytorch源码

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_printoptions(precision=3, sci_mode=False)

if __name__ == "__main__":
    run_code = 0
    batch_size = 2
    mat1_h = 3
    mat1_w = 4
    mat1_total = batch_size * mat1_w * mat1_h
    mat2_h = 4
    mat2_w = 5
    mat2_total = batch_size * mat2_w * mat2_h
    mat1 = torch.arange(mat1_total).reshape((batch_size, mat1_h, mat1_w))
    mat2 = torch.arange(mat2_total).reshape((batch_size, mat2_h, mat2_w))
    mat3 = torch.bmm(mat1, mat2)
    print(f"mat1=\n{mat1}")
    print(f"mat2=\n{mat2}")
    print(f"mat3=\n{mat3}")
  • 结果:
python 复制代码
mat1=
tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11]],

        [[12, 13, 14, 15],
         [16, 17, 18, 19],
         [20, 21, 22, 23]]])
mat2=
tensor([[[ 0,  1,  2,  3,  4],
         [ 5,  6,  7,  8,  9],
         [10, 11, 12, 13, 14],
         [15, 16, 17, 18, 19]],

        [[20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29],
         [30, 31, 32, 33, 34],
         [35, 36, 37, 38, 39]]])
mat3=
tensor([[[  70,   76,   82,   88,   94],
         [ 190,  212,  234,  256,  278],
         [ 310,  348,  386,  424,  462]],

        [[1510, 1564, 1618, 1672, 1726],
         [1950, 2020, 2090, 2160, 2230],
         [2390, 2476, 2562, 2648, 2734]]])
相关推荐
加油吧zkf5 分钟前
目标检测新纪元:DETR到Mamba实战解析
图像处理·人工智能·python·目标检测·分类
西柚小萌新11 分钟前
【深度学习:进阶篇】--4.3.seq2seq与Attention机制
人工智能·深度学习
求索小沈12 分钟前
ubuntu22.04 安装cuda cudnn
人工智能·深度学习
阿里云大数据AI技术21 分钟前
AI搜索 MCP最佳实践
数据库·人工智能·搜索引擎
大千AI助手22 分钟前
蒙特卡洛方法:随机抽样的艺术与科学
人工智能·机器学习·贝叶斯·概率·蒙特卡洛·随机
山顶望月川24 分钟前
并行科技MaaS平台支持文心4.5系列开源模型调用
人工智能·机器学习·编辑器
程序员阿超的博客32 分钟前
Python 数据分析与机器学习入门 (五):Matplotlib 数据可视化基础
python·信息可视化·数据分析·matplotlib·数据可视化·python教程·pyplot
站大爷IP1 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
python
安思派Anspire1 小时前
再见 RAG?Gemini 2.0 Flash 刚刚 “杀死” 了它!
人工智能
FF-Studio1 小时前
【硬核数学】3. AI如何应对不确定性?概率论为模型注入“灵魂”《从零构建机器学习、深度学习到LLM的数学认知》
大数据·人工智能·深度学习·机器学习·数学建模·自然语言处理·概率论