RuntimeError: bool value of Tensor with more than one value is ambiguous - image classification

Hi all together,

I have problems with using the nn.MSELoss method for image classification: RuntimeError: bool value of Tensor with more than one value is ambiguous. Size of image and label are both (8, 104) - Do you have any ideas what the problem could be?

model = EasyNet()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.5)

def train(epoch):
# Training
model.train()
for image, label in train_loader:
# Transfer to GPU
# image, label = image.to(device), label.to(device)
if image is None:
continue

    # Forward
    image = Variable(image)
    label = Variable(label)
    pred = model(image)
    print(pred.size())
    print(label.size())
    # print(pred)

optimizer.zero_grad()
loss = nn.MSELoss(pred, label)

    # Backward
    loss.backward()
    optimizer.step()
    global train_iter

You are currently trying to pass pred and label to the initialization of nn.MSELoss.
Use the functional API instead (F.mse_loss) or initialize the criterion before using it:

criterion = nn.MSELoss()
...
optimizer.zero_grad()
loss = criterion(pred, label)
...
1 Like

Thank you!! :slight_smile:

HI Ptrblck,

I chnge my loss unction from binary cross entropy to the torch.nn.CrossEntropyLoss

but it givee me this error "RuntimeError: bool value of Tensor with more than one value is ambiguous
"
The code is "

  output = netD(real_cpu).view(-1)
 label = torch.full((b_size,), real_label, device=device)
  label=torch.mul(label,0.9)      
  errD_real = criterion(output, label)

I don’t know, which line of code raises this particular error message, but nn.CrossEntropyLoss expects class indices as the target, while you seem to use soft targets.

You could use this implementation for label smoothing.