Skip to content
Advertisement

Pytorch: 1D target tensor expected, multi-target not supported

I want to train a 1D CNN on time series. I get the following error message 1D target tensor expected, multi-target not supported

Here is the code with simulated data corresponding to the structures of my data as well as the error message

JavaScript

Error message:

JavaScript

What am I doing wrong?

Advertisement

Answer

You are using nn.CrossEntropyLoss as the criterion for your training. You correctly passed the labels as indices of the ground truth class: 0s and 1s. However, as the error message suggests, it needs to be a 1D tensor!

Simply remove the reshape in ECGNet‘s __getitem__:

JavaScript

Edit

I want to increase the batch_size to 8. But now I get the error […]

You are doing a lot of broadcasting (flattening) which surely will affect the batch size. As a general rule of thumb never fiddle with axis=0. For instance, if you have an input shape of (8, 500), straight off you have a problem when doing x.view(1, 50, -1). Since the resulting tensor will be (1, 50, 80) (the desired shape would have been (8, 50, 10)). Instead, you could broadcast with x.view(x.size(0), 50, -1).

Same with x.view(1, -1) later down forward. You are looking to flatten the tensor, but you should not flatten it along with the batches, they need to stay separated! It’s safer to use torch.flatten, yet I prefer nn.Flatten which flattens from axis=1 to axis=-1 by default.


My personal advice is to start with a simple setup (without train loops etc…) to verify the architecture and intermediate output shapes. Then, add the necessary logic to handle the training.

JavaScript

Then

JavaScript

Also, make sure your loss works:

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