ValueError: Expected input batch_size (1) to match target batch_size (2)

It is from a piece of simple code

x = torch.randn(1, 100)

criterion = nn.NLLLoss()

y = np.array([1,0])

y = torch.from_numpy(y)

y=y.long()

f1=nn.Sequential(nn.Linear(100,10),nn.ReLU(),nn.Linear(10,2),nn.LogSoftmax(dim=1))

predict=f1(x)

predict=predict.squeeze()

loss = criterion(input1,y) #error from here

print(loss)


x = torch.randn(1, 100)

criterion = nn.NLLLoss()
# binary label
y = np.array([1])
# if u have K classes the target label will be made out of interegers between 0 and K-1
# in your case since you have 2 classes lables will be 0 and 1

y = torch.from_numpy(y)
y=y.long()

f1=nn.Sequential(nn.Linear(100,10),nn.ReLU(),nn.Linear(10,2),nn.LogSoftmax(dim=1))

predict=f1(x)

loss = criterion(predict,y)

print(loss)

1 Like