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

相关推荐
Pyeako23 分钟前
python网络爬虫
开发语言·爬虫·python·requsets库
diegoXie24 分钟前
【Python】 中的 * 与 **:Packing 与 Unpacking
开发语言·windows·python
_codemonster39 分钟前
深度学习实战(基于pytroch)系列(四十八)AdaGrad优化算法
人工智能·深度学习·算法
AI即插即用1 小时前
即插即用系列 | Attention GhostUNet++:基于多维注意力和 Ghost 模块的高效 CT 图像脂肪与肝脏分割网络
网络·图像处理·人工智能·深度学习·神经网络·计算机视觉·视觉检测
程序员杰哥1 小时前
如何用Postman做接口自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
xxxxxmy2 小时前
同向双指针(滑动窗口)
python·算法·滑动窗口·同向双指针
测试19982 小时前
selenium自动化测试详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
勇气要爆发2 小时前
【第一阶段—基础准备】第五章:Python模块和包管理(基础篇)—变形金刚的装备库
开发语言·python
哥布林学者2 小时前
吴恩达深度学习课程四:计算机视觉 第一周:卷积基础知识(二)卷积参数
深度学习·ai