Search code examples
pythonpytorchclassification

I am getting AttributeError: 'int' object has no attribute 'double'


While running epoch for test data I am getting the error, however for training epoch it passed.I tried to use int but that time I got error AttributeError: 'int' object has no attribute 'int'

# train loss and accuracy
train_loss = running_loss / len(dataloaders['train'].dataset)
train_acc = running_corrects.double() / len(dataloaders['train'].dataset)

print('{} Loss: {:.4f} Acc: {:.4f}'.format('train', train_loss, train_acc))

writer.add_scalar('Loss/train', train_loss,epoch)
writer.add_scalar('Accuracy/train', train_acc, epoch)

if eval:
  # set the model evaluation mode
  model.eval()

  with torch.no_grad():
    test_correct = 0
    running_loss = 0

    test_iterator = tqdm(enumerate(dataloaders['val']),
                         'Validation',
                         total=len(dataloaders['val']))
    for j, (images,labels) in test_iterator:
      images = images.to(device)
      labels = labels.to(device)

      test_outputs = model(images)

      if (len(criterion)==1):
        loss = criterion[0](outputs, labels)
      elif (len(criterion)==2):
        loss = criterion[0](outputs, labels) + criterion[1](outputs, labels)

      running_loss += loss.item()
      _, test_predicted = torch.max(test_outputs, 1)

      test_correct += torch.sum(test_predicted == labels.data)

  test_loss = running_loss / len(dataloaders['val'].dataset)
  test_acc = test_correct.double() / len(dataloaders['val'].dataset)

  writer.add_scalar('Loss/test', test_loss, epoch)
  writer.add_scalar('Accuracy/test',test_acc, epoch)

  # deep copy the model
  if train_acc > best_acc:
    best_acc = train_acc
    best_model_wts = copy.deepcopy(model.state_dict())

val_acc_history.append(test_acc)
train_accuracy.append(train_acc)
train_losses.append(train_loss)
test_accuracy.append(test_acc)
test_losses.append(test_loss)

Error: AttributeError: 'int' object has no attribute 'double'


Solution

  • In your code, test_correct is a python integer, not a pytorch tensor. Therefore it has no .double() attribute. You can change test_correct to a pytorch tensor or keep it a python int and remove the .double() call.