ValueError: Using a target size (torch.Size([491])) that is different to the input size (torch.Size([1, 491])) is deprecated. Please ensure they have the same size

Hi, I have a script that i am trying to run, but it gives the following error -

``
batch_size_16,learning_rate_0.001,epoch_times_45
selected_9606_protein_scores.csv
selected_9606_protein_scores.csv
Traceback (most recent call last):
File “/home/bvsbic/Downloads/MLtest/Validation1.py”, line 1084, in
Terms = [‘BP’, ‘MF’, ‘CC’]
File “/home/bvsbic/Downloads/MLtest/Validation1.py”, line 1065, in validation
test_set = benchmark[test_index].tolist()
File “/home/bvsbic/Downloads/MLtest/Validation1.py”, line 903, in Main
domain_train_out, domain_test_out, domain_t = Domain_train(0.001, 32, train_benchmark, test_benchmark, 45,
File “/home/bvsbic/Downloads/MLtest/Validation1.py”, line 639, in Domain_train
loss = loss_function(out, GO_annotiations)
File “/home/bvsbic/Downloads/MLtest/okenv/lib/python3.9/site-packages/torch/nn/modules/module.py”, line 727, in _call_impl
result = self.forward(*input, **kwargs)
File “/home/bvsbic/Downloads/MLtest/okenv/lib/python3.9/site-packages/torch/nn/modules/loss.py”, line 530, in forward
return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
File “/home/bvsbic/Downloads/MLtest/okenv/lib/python3.9/site-packages/torch/nn/functional.py”, line 2518, in binary_cross_entropy
raise ValueError("Using a target size ({}) that is different to the input size ({}) is deprecated. "
ValueError: Using a target size (torch.Size([491])) that is different to the input size (torch.Size([1, 491])) is deprecated. Please ensure they have the same size.

Actually, I am new here, and I don't know how to post the whole code; plz help me.

You need to ensure that the two tensors you calculate the (cross entropy) loss between have the same sizes.
See -

import torch
import torch.nn as nn

target = torch.rand(491)
print(target.size())

out = torch.rand(1, 491)
print(out.size())

loss_fn = nn.BCELoss()
loss = loss_fn(out, target) # reproduces your error

loss = loss_fn(out, target.unsqueeze(0)) # the fix
print(loss) # runs error free