pytorch(3d、4d张量转换)

维度转换

import torch

from einops import rearrange

print(torch.cuda.is_available())

to_3d

把四维的张量转换为三维的张量,输入形状(b,c,h,w),输出形状(b,hw,c)

def to_3d(x):

return rearrange(x, 'b c h w -> b (h w) c')

to_4d

把三维的张量转换为四维的张量,输入形状(b,hw,c),输出形状(b,c,h,w)

def to_4d(x,h,w):

return rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)

测试

if name == 'main':

创建一个四维张量

tensor_4d = torch.randn(2, 3, 4, 5) # 形状(批大小2, 通道数3, 高度4, 宽度5)

转换为三维张量

tensor_3d = to_3d(tensor_4d) # 形状(批大小2, 20, 3)

转换为四维张量

height, width = 4, 5

tensor_4d_back = to_4d(tensor_3d, height, width) # 形状(批大小2, 通道数3, 高度4, 宽度5)

print(tensor_4d.shape)

print(tensor_3d.shape) # 输出:torch.Size(2, 20, 3)

print(tensor_4d_back.shape) # 输出:torch.Size(2, 3, 4, 5)

相关推荐
言乐61 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle1 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
cui_ruicheng1 小时前
Python从入门到实战(六):非序列容器
开发语言·python
飞猪~2 小时前
Langchain python版本 LLM 重要函数invoke,ainvoke,stream,astream,batch,abatch
python·langchain·batch
txg6662 小时前
路径级持久化模糊测试:XSSky 如何精准击破 XSS 漏洞
深度学习·安全·web安全·网络安全·xss
向哆哆2 小时前
高质量人体检测与行人识别数据集分享(适用于YOLO系列深度学习分类检测任务)
深度学习·yolo·目标检测·分类
沙蒿同学2 小时前
当古诗词遇上 AI:从 38 万句诗词中取一个好名字
python·算法·架构
xxie1237943 小时前
Python装饰器与语法糖
开发语言·python
CClaris3 小时前
大模型量化从0到1(五):GPTQ 原理详解 + 从零量化一个真实大模型
人工智能·python·算法·机器学习
Railshiqian3 小时前
UserPickerActivity 内部逻辑分析
开发语言·python