Pytorch permute,contiguous

permute(dims),常用的维度转换方法

将tensor的维度换位      参数:dim(int)---换位顺序

>>>x = torch.randn(2,3,5)
>>>x.size()
torch.size([2,3,5])
>>>x.permute(2,0,1).size()
torch.size([5,2,3])




contiguous()

contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。
一种可能的解释是:
有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式。
判断是否contiguous用torch.Tensor.is_contiguous()函数。

import torch
x = torch.ones(10, 10)
x.is_contiguous()  # True
x.transpose(0, 1).is_contiguous()  # False
x.transpose(0, 1).contiguous().is_contiguous()  # True

在pytorch的最新版本0.4版本中,增加了torch.reshape(), 这与 numpy.reshape 的功能类似。它大致相当于 tensor.contiguous().view()

猜你喜欢

转载自www.cnblogs.com/yifdu25/p/9351841.html