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

相关推荐
知行合一。。。3 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y3 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
逻辑君3 小时前
认知神经科学研究报告【20260010】
人工智能·深度学习·神经网络·机器学习
lifewange3 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
pluvium274 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499994 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉4 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
龙文浩_4 小时前
Attention Mechanism: From Theory to Code
人工智能·深度学习·神经网络·学习·自然语言处理
ZhengEnCi4 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
微臣愚钝4 小时前
prompt
人工智能·深度学习·prompt