You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

训练正常但测试Epoch报错:'int'对象无'double'属性求助

问题分析:测试阶段触发AttributeError错误

训练Epoch可正常运行,但执行测试Epoch时出现以下错误:

Error: AttributeError: 'int' object has no attribute 'double'
尝试改用.int()方法时,又出现:
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)

错误原因

  1. 核心问题:test_correct初始化为Python原生int(test_correct = 0),但后续累加的是PyTorch张量(torch.sum(...)返回张量类型)。累加后变量会被强制转换为Python int,调用张量方法.double()自然报错。
  2. 次要笔误:测试阶段计算loss时误用了未定义的outputs变量,实际应为模型输出test_outputs,这会导致额外错误。

修复方案

  1. 初始化张量类型的计数变量:
    将test_correct初始化为同设备的PyTorch张量,和训练阶段的running_corrects保持一致:
    test_correct = torch.tensor(0, device=device)
    
  2. 修正loss计算的变量名:
    把outputs替换为test_outputs:
    if (len(criterion)==1):
        loss = criterion[0](test_outputs, labels)
    elif (len(criterion)==2):
        loss = criterion[0](test_outputs, labels) + criterion[1](test_outputs, labels)
    
  3. 可选:简化准确率计算:
    无需调用.double(),直接用张量除法即可得到浮点结果:
    test_acc = test_correct / len(dataloaders['val'].dataset)
    

内容的提问来源于stack exchange,提问作者sccomp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 14:10:15