在pytorch中转换张量形状的简单方法



输入

我有火炬张量作为休闲。

input_tensor的形状为torch.size([4,4])

input_tensor = 
tensor([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])

我将创建一个张量,通过移动大小为(2,2(的窗口来堆叠来自上述input_tensor的张量。

输出

我想要的输出如下

output_tensor的形状为torch.size([8,2])

output = 
tensor([[ 0,  1],
[ 4,  5],
[ 2,  3],
[ 6,  7],
[ 8,  9],
[12, 13],
[10, 11],
[14, 15]])

我的代码如下。

x = torch.chunk(input_tensor, chunks=2, dim=0)
x = list(x)
for i, t in enumerate(x):
x[i] = torch.cat(torch.chunk(t, chunks=2 ,dim=1))
output_tensor = torch.cat(x)

有没有一种更简单或更容易的方法来获得我想要的结果?

您可以将torch.split()torch.cat()一起使用,如下所示:

output_tensor = torch.cat(torch.split(input_tensor, 2, dim=1))

输出为:

output = 
tensor([[ 0,  1],
[ 4,  5],
[ 8,  9],
[12, 13],
[ 2,  3],
[ 6,  7],
[10, 11],
[14, 15]])

您看到的是unfolding张量:

import torch
import torch.nn.functional as nnf
input_tensor = torch.arange(16.).view(1, 1, 4, 4)
nnf.unfold(input_tensor, kernel_size=2, stride=2, padding=0).T.reshape(8,2)

关于unfoldingfolding的更多信息,请点击此处。

最新更新