Error of Cross-entropy function

criterion = nn.CrossEntropyLoss()

print(y)
print(score)

Output:
tensor([0])
tensor([-0.0582, -0.0136, -0.0489, 0.0052, -0.0133, -0.0383, 0.0546, -0.0046,
-0.0712, -0.0451, 0.0127, -0.0537, 0.0170, -0.0693, -0.0291, 0.0012,
-0.0209, -0.0789, -0.0262, -0.0246, -0.0059, 0.0020, -0.0286, 0.0061,
0.0107, -0.0366, -0.0331, 0.0319, 0.0519, 0.0404, -0.0104, -0.0366,
0.0209, 0.0137, -0.0235, -0.0217, -0.0268, -0.0281, -0.0365, -0.0068,
-0.0292, -0.0203, 0.0088, 0.0109, -0.1082, -0.0077, -0.0582, 0.0276,
0.0150, -0.0218], grad_fn=)

But if I run
loss = criterion(score, y) :

IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

But if I use output “score2” from other model’s output:

tensor([[ 0.1487, -0.0896, -0.4345, 1.4411, -0.0286, -0.8751, 0.8499, 0.3635,
0.1626, -0.6802, -0.5571, 0.1824, 0.3580, 0.1138, -1.4639, 0.4943,
-2.2529, -0.5330, -0.3036, -0.8565, -0.5219, -0.0841, -1.0277, 0.0677,
-0.8914, -0.6413, -0.6800, -0.9659, -0.6177, -0.5056, -0.1912, -0.9347,
-0.6115, -1.3679, -0.7902, -1.4691, -1.1015, -1.0402, -1.6861, -1.2793,
-1.1746, -1.6846, -1.2551, -1.9724, -1.1744, -1.6048, -1.4779, -1.9207,
-1.9850, -2.2973]], grad_fn=)

and put score2 and y in loss function, it works.

Can anybody help? If you need rest of the code, please tell.

vs

Looks like you need to score = score.unsqueeze(0) if that second example was working for you

Thank you very much!

1 Like