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)

相关推荐
kuuailetianzi6 分钟前
Python初识:定位、优势与发展历程
python
guoran_shini16 分钟前
LLM微调-训练垂类问答模型
python·lora·sft
basketball61622 分钟前
Python FastAPI 介绍以及常用方法
python·fastapi·vllm·ai infra
论文复现现场41 分钟前
企业知识库 RAG 用什么模型便宜?GLM-5.3-Flash 长文本 API 实测
python·rag·企业知识库·大模型api·glm-5.3-flash
HyperAI超神经1 小时前
HyperAI 入选 36氪「East Forward 2026 出海全球化拓新企业」
人工智能·深度学习·全球化企业
梦在远山后1 小时前
从手写 Loop 到可恢复 Runtime:用 LangGraph、PostgreSQL Checkpoint 与 AG-UI 跑通中断恢复
python·langchain·agent
Yolanda_20221 小时前
8.tensorboard的使用
python
用户0332126663672 小时前
使用 Python 添加、隐藏或删除 PowerPoint 幻灯片
python
言乐62 小时前
Python关键词抓取目标网站
python·django·virtualenv·pygame·tornado
用户7783366132112 小时前
搜索页的 URL 状态管理:可分享、可回退、可刷新
python·api