网络编程
位置:首页>> 网络编程>> Python编程>> PyTorch中的squeeze()和unsqueeze()解析与应用案例

PyTorch中的squeeze()和unsqueeze()解析与应用案例

作者:易烊千蝈  发布时间:2022-09-22 23:04:49 

标签:PyTorch,squeeze(),unsqueeze()

附上官网地址:

https://pytorch.org/docs/stable/index.html

1.torch.squeeze

PyTorch中的squeeze()和unsqueeze()解析与应用案例

squeeze的用法主要就是对数据的维度进行压缩或者解压。

先看torch.squeeze() 这个函数主要对数据的维度进行压缩,去掉维数为1的的维度,比如是一行或者一列这种,一个一行三列(1,3)的数去掉第一个维数为一的维度之后就变成(3)行。squeeze(a)就是将a中所有为1的维度删掉。不为1的维度没有影响。a.squeeze(N) 就是去掉a中指定的维数为一的维度。还有一种形式就是b=torch.squeeze(a,N) a中去掉指定的定的维数为一的维度。

换言之:

表示若第arg维的维度值为1,则去掉该维度,否则tensor不变。(即若tensor.shape()[arg] == 1,则去掉该维度)

例如:

一个维度为2x1x2x1x2的tensor,不用去想它长什么样儿,squeeze(0)就是不变,squeeze(1)就是变成2x2x1x2。(0是从最左边的维度算起的)

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])

2.torch.unsqueeze

PyTorch中的squeeze()和unsqueeze()解析与应用案例

torch.unsqueeze()这个函数主要是对数据维度进行扩充。给指定位置加上维数为一的维度,比如原本有个三行的数据(3),在0的位置加了一维就变成一行三列(1,3)。a.squeeze(N) 就是在a中指定位置N加上一个维数为1的维度。还有一种形式就是b=torch.squeeze(a,N) a就是在a中指定位置N加上一个维数为1的维度。

>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

3.例子

给一个使用上述两个函数,并进行一次卷积的例子:

from torchvision.transforms import  ToTensor
import torch as t
from torch import nnimport cv2
import numpy as np
import cv2
to_tensor = ToTensor()
# 加载图像
lena = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('lena', lena)
# input = to_tensor(lena) 将ndarray转换为tensor,自动将[0,255]归一化至[0,1]。
input = to_tensor(lena).unsqueeze(0)
# 初始化卷积参数
kernel = t.ones(1, 1, 3, 3)/-9
kernel[:, :, 1, 1] = 1
conv = nn.Conv2d(1, 1, 3, 1, padding=1, bias=False)
conv.weight.data = kernel.view(1, 1, 3, 3)
# 输出
out = conv(input)
out = out.squeeze(0)
print(out.shape)
out = out.unsqueeze(3)
print(out.shape)
out = out.squeeze(0)
print(out.shape)
out = out.detach().numpy()# 缩放到0~最大值
cv2.normalize(out, out, 1.0, 0, cv2.NORM_INF)
cv2.imshow("lena-result", out)
cv2.waitKey()

结果图如下:

PyTorch中的squeeze()和unsqueeze()解析与应用案例

references:
[1] 陈云.深度学习框架之PyTorch入门与实践.北京:电子工业出版社,2018.

来源:https://blog.csdn.net/weixin_39490300/article/details/123464027

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com