np.transpose(),torch.permute(),tensor.permute()

 

在完成两个维度转换时效果一样,只不过transpose是对np操作,permute是对tensor操作;

transpose每次只能换两个维度,两种写法,参数顺序无所谓;

permute每次可以交换多个维度,但所有的维度也必须都写上,参数顺序表示交换结果是原值的哪个维度,只有一种写法。

注意:使用transpose或permute之后,若要使用view,必须先contiguous()

 

python切片:
data = torch.randint(0, 100, (4, 5, 3), dtype = torch.float32)
print(data)
list_1 = [0, 1, 2, 3]
list_2 = [2, 4, 3, 0]
#第一维中,每一维都取出2,4,3,0的第二维
print(data[:, list_2, :])
#第一维中第0个取第二维中的第2个,1取4,2取3,3取0
print(data[list_1, list_2, :])

 

  • permute一次可以操作多个维度,并且必须传入所有维度数;而transpose只能同时交换两个维度,并且只能传入两个数;
  • permute可以通过多个transpose实现;
  • transpose传入的dim无顺序之分,传入(1,0)和(0,1)结果一样,都是第一维度和第二维度进行交换;permute传入的dim有顺序之分,传入(0,1)代表交换后原第一维度在前面,原第二维度在后面;传入(1,0)代表交换后原第二维度在前面,原第一维度在后面;。

在计算机视觉中,由于cv2格式(numpy)读取的图片为H×W×C,通道数在最后;而torch中的图片常以C×H×W存在,因此,当图片在tensor与numpy之间转换时,需要用到交换数组维度的函数来将图片存储格式转化。

 

np.transpose()

numpy.transpose(aaxes=None)[source]

https://numpy.org/devdocs/reference/generated/numpy.transpose.html

Returns an array with axes transposed.

For a 1-D array, this returns an unchanged view of the original array, as a transposed vector is simply the same vector. To convert a 1-D array into a 2-D column vector, an additional dimension must be added, e.g., np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is the standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided, then transpose(a).shape == a.shape[::-1].

Parameters:
aarray_like

Input array.

axestuple or list of ints, optional

If specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.

Returns:
pndarray

a with its axes permuted. A view is returned whenever possible.

 

 

torch.transpose——交换两个维度

torch.transpose(input, dim0, dim1) → Tensor

功能:将输入数组的dim0维度和dim1维度交换

输入:

  • input:需要做维度交换的数组
  • dim0dim1:交换的维度

注意:

  • 返回的张量数组与原来的数组共享底层存储,更改一方的数据内容,另一方的数据也会被修改;
  • 只能同时交换两个维度,因此只能输入两个数;
  • torch.transpose也可以通过a.transpose实现,后者默认转换数组a;
  • 经过交换后的内存地址不连续,如果用view改变视图,则会报错。

tensor.permute——交换多个维度

tensor.permute(*dims) → Tensor

功能:将数组tensor的维度按输入dims的顺序进行交换

输入:

  • dims:维度交换顺序

注意:

  • transpose类似经过交换后的内存地址不连续,如果用view改变视图,则会报错
  • tensor.permute的功能与np.transpose类似,均可以同时对一个数组进行多维度交换操作

 

 

posted on 2022-12-09 15:00  lmqljt  阅读(592)  评论(0编辑  收藏  举报

导航