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

相关推荐
华农DrLai2 小时前
什么是LLM做推荐的三种范式?Prompt-based、Embedding-based、Fine-tuning深度解析
人工智能·深度学习·prompt·transformer·知识图谱·embedding
2301_764441332 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
chushiyunen3 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA3 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
baidu_huihui3 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
高洁013 小时前
多模态AI模型融合难?核心问题与解决思路
人工智能·深度学习·机器学习·数据挖掘·transformer
南 阳3 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙3 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
FreakStudio4 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy