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])

相关推荐
aaaa_a1338 分钟前
李宏毅——self-attention Transformer
人工智能·深度学习·transformer
工会代表19 分钟前
使用 GitHub Actions 与 Docker 实现 CaptchaVision API 持续集成
python
cvyoutian28 分钟前
解决 PyTorch 大型 wheel 下载慢、超时和反复重下的问题
人工智能·pytorch·python
子非鱼92138 分钟前
3 传统序列模型——RNN
人工智能·rnn·深度学习
万俟淋曦40 分钟前
【论文速递】2025年第33周(Aug-10-16)(Robotics/Embodied AI/LLM)
人工智能·深度学习·ai·机器人·论文·robotics·具身智能
小徐敲java1 小时前
python的FastAPI框架
开发语言·python·fastapi
像风没有归宿a1 小时前
AI绘画与音乐:生成式艺术是创作还是抄袭?
人工智能·深度学习·计算机视觉
CHANG_THE_WORLD1 小时前
Python 切片操作全面解析
开发语言·python
碧海银沙音频科技研究院1 小时前
基于物奇wq7036与恒玄bes2800智能眼镜设计
arm开发·人工智能·深度学习·算法·分类
是一个Bug2 小时前
Spring事件监听器在电商订单系统中的应用
java·python·spring