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

相关推荐
青瓷程序设计12 分钟前
基于YOLO的火灾烟雾检测系统~Python+目标检测+算法模型+2026原创
python·yolo·目标检测
立莹Sir13 分钟前
Spring Bean 生命周期详解
java·python·spring
JHC0000006 小时前
基于Ollama,Milvus构建的建议知识检索系统
人工智能·python·milvus
mOok ONSC6 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
GIS兵墩墩7 小时前
postgis--PostgreSQL16及其plpython3u扩展
python·postgis
new Object ~7 小时前
LangChain的短期记忆存储实现
python·langchain
魔都吴所谓7 小时前
【Python】从零构建:IP地理位置查询实战指南
开发语言·python·tcp/ip
测试19988 小时前
使用Python自动化生成接口测试用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
程序员Shawn8 小时前
【深度学习 | 第一篇】- Pytorch与张量
人工智能·pytorch·深度学习