Help understanding nn.NLLLoss example

Hello,

I was reading pytorch documentation on nn.NLLLoss module. I tried out the following example provided:

2D loss example (used, for example, with image inputs)

N, C = 5, 4
loss = nn.NLLLoss()

input is of size N x C x height x width

data = torch.randn(N, 16, 10, 10)
m = nn.Conv2d(16, C, (3, 3))

each element in target has to have 0 <= value < C

target = torch.tensor(N, 8, 8).random_(0, C)
output = loss(m(data), target)
output.backward()

but I get this error instead.
ValueError: Expected input batch_size (5) to match target batch_size (3).

Thanks for in advance for the help and assistances!

Could you try to run this single line of code:

target = torch.tensor(N, 8, 8).random_(0, C)

Do you get an error or was it successful?

I get this error:
TypeError: tensor() takes 1 positional argument but 3 were given

Thanks for the info.
Could you change it to

target = torch.Tensor(N, 8, 8).random_(0, C)

and run it again? (Note the uppercase T in Tensor)

Ok, this time no error, however when I proceed to run the next line:
output = loss(m(data), target)

I get this error:
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 ‘target’

Try to cast the tensor so long by

target = target.long()

Which PyTorch version are you using?

Ah, that worked, thank you very much! I understand it better now

I’m currently running python 3.6 and and pytorch 0.4.0