How do I use one-hot encoding with cross-entropy loss?
I have tried using one-hot encoding for a multiclass classification of about 120 classes using a dog breed dataset. Also using resnet18. But the following error is shown when I run the code. Please help me solve the issue.

The code of my model is shown below:

model = torchvision.models.resnet18()
op = torch.optim.Adam(model.parameters(),lr=0.001)
crit = nn.NLLLoss()
model.fc = nn.Sequential(
    nn.Linear(512,120),
    nn.Dropout(inplace=True),
    nn.ReLU(),
    nn.LogSoftmax())

for i,(x,y) in enumerate(train_dl):
    # prepare one-hot vector
    y_oh=torch.zeors(y.shape[0],120)
    y_oh.scatter_(1, y.unsqueeze(1), 1)

    # do the prediction
    y_hat=model(x)
    y_=torch.max(y_hat)

    loss=crit(y,y_)
    op.zero_grad()
    loss.backward()
    op.step()


The error:

RuntimeError Traceback (most recent call last) &lt;ipython-input-190-46a21ead759a&gt; in &lt;module&gt;
       6 
       7     y_hat=model(x)
 ----&gt; 8     loss=crit(y_oh,y_hat)
       9     op.zero_grad()
      10     loss.backward()

***RuntimeError: 1D target tensor expected, multi-target not supported***


The NLLLoss you are using expects indices of the ground-truth target classes. Btw. you do not have to convert your targets into one-hot vectors and use directly the y tensor.

Note also that NLLLoss expect the distribution output distribution in the logarithmic domains, i.e., use nn.LogSoftmax instead of nn.Softmax.
