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)

相关推荐
一条大祥脚1 小时前
TVM 的前世今生:从深度学习编译器到 AI 基础设施
人工智能·深度学习·tvm
❁满城风絮*1 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天3 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读3 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户8356290780514 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
用户8356290780515 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
AI源码5 小时前
基于深度学习的音乐风格分类系统
人工智能·深度学习
特立独行的猫A5 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
深蓝AI5 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
田里的水稻5 小时前
FA_CNN卷积神经网络二十七---填充与步幅PyTorch
人工智能·pytorch·cnn