Pytorch reshape tensor dimension(Pytorch 重塑张量维度)
问题描述
例如,我有一个维度为 (5) 的一维向量.我想将其重塑为二维矩阵 (1,5).
这是我如何使用 numpy
<预><代码>>>>将 numpy 导入为 np>>>a = np.array([1,2,3,4,5])>>>一个形状(5,)>>>a = np.reshape(a, (1,5))>>>一个形状(1, 5)>>>一个数组([[1, 2, 3, 4, 5]])>>>但是我怎么能用 Pytorch 张量(和变量)做到这一点.我不想切换回 numpy 并再次切换到 Torch 变量,因为它会丢失反向传播信息.
这是我在 Pytorch 中的内容
<预><代码>>>>进口火炬>>>从 torch.autograd 导入变量>>>a = torch.Tensor([1,2,3,4,5])>>>一个12345[大小为 5 的torch.FloatTensor]>>>a.size()(5L,)>>>a_var = 变量(a)>>>a_var = 变量(a)>>>a_var.size()(5L,).....在前向函数中做一些计算>>>a_var.size()(5L,)现在我希望它的大小为 (1, 5).如何在不丢失毕业信息的情况下调整变量中 pytorch 张量的尺寸或重塑其尺寸.(因为我会在倒退之前输入另一个模型)
使用 torch.unsqueeze(input, dim, out=None)
For example, I have 1D vector with dimension (5). I would like to reshape it into 2D matrix (1,5).
Here is how I do it with 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]])
>>>
But how can I do that with Pytorch Tensor (and Variable). I don't want to switch back to numpy and switch to Torch variable again, because it will loss backpropagation information.
Here is what I have in 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,)
Now I want it size to be (1, 5). How can I resize or reshape the dimension of pytorch tensor in Variable without loss grad information. (because I will feed into another model before backward)
Use 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]
这篇关于Pytorch 重塑张量维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!