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)

相关推荐
ai小陈1 小时前
PyTorch Profiler性能分析实战:定位GPU训练中的慢算子
人工智能·深度学习·机器学习·ai·性能优化·gpu算力
YCOSA20252 小时前
系统工具使用检测.exe (仅供娱乐)
python·microsoft
2601_962295332 小时前
如何python实现网页的自动化
python·selenium·beautifulsoup·requests·网页自动化
ofoxcoding2 小时前
GPT Image 2.5 API 实战:Python 调用实现图片生成与编辑
人工智能·python·gpt·ai
张小姐的猫3 小时前
【AI大模型接入SDK】 —— Gemini接入封装
android·数据结构·数据库·c++·人工智能·python
Elastic 中国社区官方博客3 小时前
Elasticsearch Python DSL 客户端开发
大数据·数据库·python·elasticsearch·搜索引擎·全文检索
计算机编程-吉哥4 小时前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】
人工智能·python·深度学习·算法·毕业设计·课程设计·大数据毕业设计选题推荐
小木_.4 小时前
Python 离线识别滑块缺口距离,项目推荐
开发语言·python·滑块识别·人机验证·滑块缺口·缺口识别
Cenxi4 小时前
Python字符串方法练习手册
人工智能·python
liliangcsdn4 小时前
因子权重矩阵处理-因子权重收缩Shrinkage算法的探索
开发语言·python·机器学习