【数据结构与算法】PyTorch中permute与contiguous对tensor结构进行变换
作者:互联网
contiguous()——把tensor变成在内存中连续分布的形式
需要变成连续分布的情况:
contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。
import torch
import numpy as nn
def main():
myArr = np.array([[[1,2,3],
[4,5,6]]])
print(myArr.shape)
print(myArr.size)
myTsr = torch.tensor(myArr)
print(myTsr)
print(myTsr.shape)
myTsr2 = myTsr.permute(2,0,1)
print(myTsr2)
print(myTsr2.shape)
myTsr3 = myTsr2.contiguous().view(-1,2)
print(myTsr3)
print(myTsr3.shape)
if __name__ == '__main__':
main()
运行结果:
(1, 2, 3)
6
tensor([[[1, 2, 3],
[4, 5, 6]]], dtype=torch.int32)
torch.Size([1, 2, 3])
tensor([[[1, 4]],
[[2, 5]],
[[3, 6]]], dtype=torch.int32)
torch.Size([3, 1, 2])
tensor([[1, 4],
[2, 5],
[3, 6]], dtype=torch.int32)
torch.Size([3, 2])
标签:__,tensor,contiguous,torch,PyTorch,print,myArr 来源: https://blog.csdn.net/bigFatCat_Tom/article/details/97170387