qim*_*ang 6 python neural-network reshape deep-learning pytorch
我将获得一个变量中的每个水平张量,但我丢失了一个维度。
这是我的代码:
import torch
from torch.autograd import Variable
t = torch.rand((2,2,4))
x = Variable(t)
print(x)
shape = x.size()
for i in range(shape[0]):
for j in range(shape[1]):
print(x[i,j])
Run Code Online (Sandbox Code Playgroud)
输出是:
Variable containing:
(0 ,.,.) =
0.6717 0.8216 0.5100 0.9106
0.3280 0.8182 0.5781 0.3919
(1 ,.,.) =
0.8823 0.4237 0.6620 0.0817
0.5781 0.4187 0.3769 0.0498
[torch.FloatTensor of size 2x2x4]
Variable containing:
0.6717
0.8216
0.5100
0.9106
[torch.FloatTensor of size 4]
Variable containing:
0.3280
0.8182
0.5781
0.3919
[torch.FloatTensor of size 4]
Variable containing:
0.8823
0.4237
0.6620
0.0817
[torch.FloatTensor of size 4]
Variable containing:
0.5781
0.4187
0.3769
0.0498
[torch.FloatTensor of size 4]
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到 [torch.FloatTensor of size 1x4]?
在你的例子中,x是一个 2x2x4 张量。因此,当您这样做时,x[0]您将获得第一行中的 2x4 张量。如果这样做,x[i,j]您将获得位置 (i,j) 的 4 维向量。如果您想保留其中一个维度,您可以使用切片:x[i,j:j+1]或重塑张量:x[i,j].view(1,4)。因此你的代码看起来像:
import torch
from torch.autograd import Variable
t = torch.rand((2,2,4))
x = Variable(t)
print(x)
shape = x.size()
for i in range(shape[0]):
for j in range(shape[1]):
print(x[i,j:j+1])
Run Code Online (Sandbox Code Playgroud)
或者
import torch
from torch.autograd import Variable
t = torch.rand((2,2,4))
x = Variable(t)
print(x)
shape = x.size()
for i in range(shape[0]):
for j in range(shape[1]):
print(x[i,j].view(1,4)
Run Code Online (Sandbox Code Playgroud)
会给你想要的结果。
编辑:
是的,或者正如 nnnmmm 的答案中提到的, torch.unsqueeze(x[i, j], 0)也可以工作,因为它在第 0 个位置添加了大小为 1 的维度。