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)

相关推荐
岁月宁静5 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者5 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy19907 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk5558 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~14 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享15 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者16 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.16 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
哈尔滨张谦蛋16 小时前
兰州大学 · 甘肃省可穿戴装备重点实验室 · 2027年博士招生
人工智能·深度学习
the局外人17 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python