Skip to content

CrossEntropyLoss input dimension ERROR #3947

Closed

Description

@ogugugugugua

From the doc of pytorch we know the use of crossentropy loss should be like this :

The input is expected to contain scores for each class.
input has to be a 2D Tensor of size (minibatch, C).
This criterion expects a class index (0 to C-1) as the
target for each value of a 1D tensor of size minibatch
And
Shape:
- Input: :math:(N, C) where C = number of classes
- Target: :math:(N) where each value is 0 <= targets[i] <= C-1

And the example from the doc is :

 loss = nn.CrossEntropyLoss()
 input = autograd.Variable(torch.randn(3, 5), requires_grad=True)
 target = autograd.Variable(torch.LongTensor(3).random_(5))
 output = loss(input, target)
 output.backward()

As a beginner of pytorch, I am confused of the dimension of the input & target.

  1. If we like to compare how the input is similar to the target, and the classes of the input is C, why the dimension of target is N but not C, since target should have a score for each of its classes, then the comparation between them can happen. Can someone tell me what the dimension of the input and especially the target mean, why we should have a dimension of "minibatch" here for the target? Or maybe I misunderstood it?
  2. In my classifier project I am trying to compare the loss between target and the output of model using crossentropy. Both of them are NOT one-hot. The sizes of them are: Target(5518), Output(1,5518). I'm trying to indicate that there're 5518 classes, my model gives all the classes a score which is storaged in Output tensor, and the 1-D Target tensor, of course storage the right classification answer. All I wanna do is to compare the similarity between them, but how can I do that...?

Appreciate a lot if someone can do me a favor! Thanks in advance!! 🥇

Activity

  1. ssnl commented on Nov 30, 2017

    @ssnl
    Collaborator
    1. N stands for batch size. So input is the network outputs of N input data. C is the number of classes. Each value in target means the correct class of the corresponding input data. Note that target is not one-hot encoded but just simply the class indices.
    2. Your target should be only size (1,) for reasons above.

    Finally, since Github is used for tracing bugs / feature requests, this type of post is better placed at discuss.pytorch.org. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions