torch.unsqueeze、np.expand_dims详解

超链接:深度学习工作常用方法汇总,矩阵维度变化、图片、视频等操作,包含(torch、numpy、opencv等)


增加维度 : unsqueeze、np.expand_dims

torch版:

x.unsqueeze(dim=0)

简介:

将矩阵x在dim=0维度上增加一个维度。 [3, 3, 2] -->>-- [1, 3, 3, 2]
可以理解为,在dim=n的前面增加一个维度。索引从0开始

用途之一:torch 模型训练中dataloader函数返回的数据为[batch, 3, 224, 224]大小的数据,会增加一个batch维度,但是我们在预测的时候,一般都是一张图片直接进入模型,进行预测,可是模型的输入需要batch维度,我们为了维度对应,一般都用 增加维度的方法实现。

torch示例:

import torch
import numpy as np

x = torch.rand((2, 2, 3, 3))
b = x.unsqueeze(0)
c = x.unsqueeze(1)
d = x.unsqueeze(2)
print('x_shape:', x.shape)  # torch.Size([2, 2, 3, 3])
print('b_shape:', b.shape)  # b_shape: torch.Size([1, 2, 2, 3, 3])
print('c_shape:', c.shape)  # c_shape: torch.Size([2, 1, 2, 3, 3])
print('d_shape:', d.shape)  # d_shape: torch.Size([2, 2, 1, 3, 3])

numpy版:

np.expand_dims(arr, 0)

numpy示例:

import torch
import numpy as np

x = np.array(([1, 2], [3, 4]))
b = np.expand_dims(x, axis=0)
c = np.expand_dims(x, axis=1)
print('x_shape:', x.shape)  # (2, 2)
print('b_shape:', b.shape)  # b_shape: (1, 2, 2)
print('c_shape:', c.shape)  # c_shape: (2, 1, 2)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python图像识别

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值