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

相关推荐
HyperAI超神经几秒前
【vLLM 学习】Rlhf Utils
人工智能·深度学习·学习·机器学习·ai编程·vllm
qwerasda1238524 分钟前
车牌字符识别与定位技术:多国家车牌检测与识别系统
python
独行soc9 分钟前
2026年渗透测试面试题总结-3(题目+回答)
网络·python·安全·web安全·渗透测试
sg_knight19 分钟前
工厂方法模式(Factory Method)
java·服务器·python·设计模式·工厂方法模式·工厂模式
西红市杰出青年29 分钟前
Python异步----------信号量
开发语言·python
tianyuanwo34 分钟前
深入浅出SWIG:从C/C++到Python的无缝桥梁
c语言·c++·python·swig
金融小白数据分析之路43 分钟前
msoffcrypto-tool库 Excel 加密
python·excel
程序员敲代码吗1 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
a程序小傲1 小时前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
一名机电研究生1 小时前
电机驱动系统智能监测与故障预测技术指南:构建数据驱动的预防性维护体系
python·sql·诊断预测