Pytorch reshape tensor dimension

前端 未结 10 550
忘掉有多难
忘掉有多难 2021-02-03 17:56

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 num         


        
10条回答
  •  花落未央
    2021-02-03 18:26

    This question has been thoroughly answered already, but I want to add for the less experienced python developers that you might find the * operator helpful in conjunction with view().

    For example if you have a particular tensor size that you want a different tensor of data to conform to, you might try:

    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)
    

    This works with numpy shape too:

    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)
    

提交回复
热议问题