2017-04-10 116 views
13

例如,我有維數爲(5)的一維向量。我想將它重新塑造成2D矩陣(1,5)。Pytorch重塑張量維數

這裏是我如何做到這一點與numpy的

>>> import numpy as np 
>>> a = np.array([1,2,3,4,5]) 
>>> a.shape 
(5,) 
>>> a = np.reshape(a, (1,5)) 
>>> a.shape 
(1, 5) 
>>> a 
array([[1, 2, 3, 4, 5]]) 
>>> 

但我怎麼能做到這一點與Pytorch張量(和變量)。我不想切換回numpy並再次切換到Torch變量,因爲它會丟失反向傳播信息。

這是我在Pytorch

>>> import torch 
>>> from torch.autograd import Variable 
>>> a = torch.Tensor([1,2,3,4,5]) 
>>> a 

1 
2 
3 
4 
5 
[torch.FloatTensor of size 5] 

>>> a.size() 
(5L,) 
>>> a_var = variable(a) 
>>> a_var = Variable(a) 
>>> a_var.size() 
(5L,) 
.....do some calculation in forward function 
>>> a_var.size() 
(5L,) 

現在我想它的尺寸爲(1,5)。 如何在變量中調整或重新設置pytorch張量的維數而不丟失grad信息。 (因爲我會喂到另一個模型前向後)

回答

8

使用torch.unsqueeze(input, dim, out=None)

>>> import torch 
>>> a = torch.Tensor([1,2,3,4,5]) 
>>> a 

1 
2 
3 
4 
5 
[torch.FloatTensor of size 5] 

>>> a = a.unsqueeze(0) 
>>> a 

1 2 3 4 5 
[torch.FloatTensor of size 1x5] 
11

您可以使用

a.view(1,5) 
Out: 

1 2 3 4 5 
[torch.FloatTensor of size 1x5] 
+0

注意這**不**修改原始張'了'。它只是創建一個視圖。 – kmario23

4

,或者你可以利用這一點,在「-1」意味着你不必須指定元素的數量。

In [3]: a.view(1,-1) 
Out[3]: 

1 2 3 4 5 
[torch.FloatTensor of size 1x5] 
1

這個問題已經被徹底地已經回答了,但我想補充的經驗較少的Python開發人員,你可能會發現在結合了*運營商大有裨益的view()

例如,如果你有你想要的數據以符合不同的張特定的張量的大小,你可以嘗試:

img = Variable(tensor.randn(20,30,3)) # tensor with goal shape 
flat_size = 20*30*3 
X = Variable(tensor.randn(50, flat_size)) # data tensor 

X = X.view(-1, *img.size()) # sweet maneuver 
print(X.size()) # size is (50, 20, 30, 3) 

這適用於numpy的shape太:

img = np.random.randn(20,30,3) 
flat_size = 20*30*3 
X = Variable(tensor.randn(50, flat_size)) 
X = X.view(-1, *img.shape) 
print(X.size()) # size is (50, 20, 30, 3) 
3

對於就地修改的張量,你一定要使用 tensor.resize_()

In [23]: a = torch.Tensor([1, 2, 3, 4, 5]) 

In [24]: a.shape 
Out[24]: torch.Size([5]) 


# tensor.resize_((`new_shape`))  
In [25]: a.resize_((1,5)) 
Out[25]: 

1 2 3 4 5 
[torch.FloatTensor of size 1x5] 

In [26]: a.shape 
Out[26]: torch.Size([1, 5]) 

在PyTorch,如果有在操作結束時的下劃線(像tensor.resize_()),然後該操作確實in-place修改爲原始張量。


此外,您可以簡單地在火炬張量中使用np.newaxis來增加尺寸。這裏有一個例子:

In [34]: list_ = range(5) 
In [35]: a = torch.Tensor(list_) 
In [36]: a.shape 
Out[36]: torch.Size([5]) 

In [37]: new_a = a[np.newaxis, :] 
In [38]: new_a.shape 
Out[38]: torch.Size([1, 5])