Convert 1d tensor to 2d tensor

Hi I am new to pytorch , I just wanted to convert 1 dimensional tensor to 2 dimensional tensor but when I use tensor.view() it my code still throws a dimensionality problem.please help

1 Like

You can’t change the number of elements in the tensor, so you’re likely calculating the dimensions wrong. If you have a 100 element tensor, you can’t view it to x.view(20,10) because that would require you to have 20*10=200 elements. Try just taking a 100 element tensor and running x.view(1,100,1) and you’ll see how you can arbitrarily add dimensions.

1 Like

If it’s a tensor and not a variable you can also use unsqueeze to add a dummy dimension

1 Like

I have done like this before:

import torch
x_train  = torch.linspace(-1, 1, 101)    # 1D tensor
print(x_train.size())
# torch.Size([101])   

x_train = x_train.view(101, 1)          # convert to 2D tensor
print(x_train.size())
# torch.Size([101, 1])

If you have a tensor img with a size

torch.Size([784])

and you want to convert it to a size of

torch.Size([1, 784])

you can call the resize_ method like below:

img.resize_(1, 784)

I would consider the usage of resize_ to be dangerous and applicable for advanced use cases, and would thus recommend to use tensor.view(1, -1) or tensor.unsqueeze(0) for this use case.
From the docs of resize_:

This is a low-level method. The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged). For most purposes, you will instead want to use view() , which checks for contiguity, or reshape() , which copies data if needed. To change the size in-place with custom strides, see set_() .

1 Like