torch.unsqueeze、np.expand_dims详解

1. 增加维度 : unsqueeze、np.expand_dims

torch版:

x.unsqueeze(dim=0)

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

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)

你可能感兴趣的:(人工智能,numpy,python,torch,深度学习,计算机视觉)