Skip to content
Advertisement

This torch project keep telling me “Expected 2 or more dimensions (got 1)”

I was trying to make my own neural network using PyTorch. I do not understand why my code is not working properly.

JavaScript

The program keeps giving me this error:

Expected 2 or more dimensions (got 1)

Can anyone explain what is wrong with my code?

Advertisement

Answer

The tensor you use as the dataset, Xs is shaped (n, 2). So when looping over it each element x ends up as a 1D tensor shaped (2,). However, your module expects a batched tensor as input, i.e. here a 2D tensor shaped (n, 2), just like Xs. You have two possible options, either use a data loader and divide your dataset into batches, or unsqueeze your input x to make it two dimensional shaped (1, 2).

  • Using a TensorDataset and wrapping it with a DataLoader:

    JavaScript

    Then iterating over dataloader will return batches of fours (inputs and corresponding labels):

    JavaScript

    TensorDataset and Dataloader are both imported from torch.utils.data.

  • Or use torch.Tensor.unsqueeze on x to add one extra dimension:

    JavaScript

    Alternatively, you can do x[None] which has the same effect.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement