【python深度学习】——torch.einsum|torch.bmm

【python深度学习】------torch.einsum|torch.bmm

  • [1. 基本用法与示例](#1. 基本用法与示例)
  • [2. torch.bmm](#2. torch.bmm)

1. 基本用法与示例

基本用法:

python 复制代码
torch.einsum(equation, *operands)
  • equation: 一个字符串,定义了张量操作的模式。
    使用逗号来分隔输入张量的索引,然后是一个箭头(->),接着是输出张量的索引。
  • operands: 要操作的张量。
    示例代码:
python 复制代码
import torch
A = torch.randn(2, 3)

B = torch.einsum('ij->ji', A)
# 等价于 B = A.transpose(0, 1)

C = torch.einsum('ik,kj->ij', A, B)
# 等价于 C = torch.matmul(A, B)

a = torch.randn(3)
b = torch.randn(3)
c = torch.einsum('i,i->', a, b)
# 等价于 c = torch.dot(a, b)


A = torch.randn(5, 2, 3)
B = torch.randn(5, 3, 4)
C = torch.einsum('bij,bjk->bik', A, B)
# 等价于 C = torch.bmm(A, B)


a = torch.randn(3)
b = torch.randn(4)
c = torch.einsum('i,j->ij', a, b)
# 结果是一个3x4的矩阵,等价于 c = a.unsqueeze(1) * b.unsqueeze(0)


A = torch.randn(3, 3)
trace = torch.einsum('ii->', A)
# 等价于 trace = torch.trace(A)

2. torch.bmm

全称为: batch matrix-matrix product, 批量矩阵乘法, 适用于三维张量,其中第一维表示批量大小,第二维和第三维表示矩阵的行和列

python 复制代码
torch.bmm(input, mat2, *, out=None) -> Tensor
  • input: 一个形状为 (b, n, m) 的三维张量,表示一批矩阵。
  • mat2: 一个形状为 (b, m, p) 的三维张量,表示另一批矩阵。
  • out (可选): 存储输出结果的张量。
    输出是一个形状为 (b, n, p) 的张量,其中每个矩阵是对应批次的矩阵乘法结果。

例如:

python 复制代码
import torch

# 定义两个形状为 (b, n, m) 和 (b, m, p) 的三维张量
batch_size = 10
n, m, p = 3, 4, 5

A = torch.randn(batch_size, n, m)
B = torch.randn(batch_size, m, p)

# 进行批量矩阵乘法
C = torch.bmm(A, B)

print(C.shape)  # 输出: torch.Size([10, 3, 5])

再具体的:

python 复制代码
A = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
B = torch.tensor([[[9, 10], [11, 12]], [[13, 14], [15, 16]]])

# A.shape = (2, 2, 2)
# B.shape = (2, 2, 2)
C = torch.bmm(A, B)

print(C)
# 输出:
# tensor([[[ 31,  34],
#          [ 73,  80]],
#
#         [[155, 166],
#          [211, 226]]])

其数学计算为:

相关推荐
Suckerbin4 分钟前
第十一章-PHP表单传值
开发语言·php
fantasy_424 分钟前
LeetCode238☞除自身以外数组的乘积
java·数据结构·python·算法·leetcode
Tech Synapse29 分钟前
零基础搭建AI作曲工具:基于Magenta/TensorFlow的交互式音乐生成系统
人工智能·python·tensorflow
元亓亓亓30 分钟前
Java后端开发day38--不可变集合&Stream流
java·开发语言
努力创造奇迹34 分钟前
C 语言联合体、枚举、typedef 详解
c语言·开发语言
纪元A梦37 分钟前
华为OD机试真题——阿里巴巴找黄金宝箱Ⅰ(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
java·c语言·javascript·c++·python·华为od·go
AI_RSER1 小时前
Python 数据可视化全场景实现(一)
开发语言·人工智能·python·信息可视化·遥感
eqwaak01 小时前
Matplotlib高阶技术全景解析(续):动态交互、三维可视化与性能优化
开发语言·python·语言模型·性能优化·交互·matplotlib
愚润求学1 小时前
【专题四】前缀和(3)
开发语言·c++·笔记·leetcode·刷题·c++11
蜗牛沐雨1 小时前
Pandas 数据导出:如何将 DataFrame 追加到 Excel 的不同工作表
python·excel·pandas