火炬重塑张量尺寸 [英] Pytorch reshape tensor dimension

查看:103
本文介绍了火炬重塑张量尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有尺寸为(5)的一维矢量.我想将其重塑为2D矩阵(1,5).

For example, I have 1D vector with dimension (5). I would like to reshape it into 2D matrix (1,5).

这是我用numpy进行的操作

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]])
>>> 

但是我该如何使用Pytorch Tensor(和Variable)来做到这一点.我不想再次切换到numpy并再次切换到Torch变量,因为它将丢失反向传播信息.

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.

这就是我在Pytorch中拥有的东西

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,)

现在,我希望它的大小为(1,5). 如何在不丢失损失等级信息的情况下,在变量"中调整pytorch张量的大小或形状. (因为我将向后输入另一个模型)

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)

推荐答案

使用 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]

这篇关于火炬重塑张量尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆