【问题标题】:Image classification Using Pytorch使用 Pytorch 进行图像分类
【发布时间】:2021-01-27 09:33:43
【问题描述】:

这是我使用 Pytorch 进行图像分类的代码,但我无法获得正确的准确性。 精度超过100,谁能帮我找出错误。

     def trained_model(criterion, optimizer, epochs=5):

      epoch_loss = 0.0
      epoch_accuracy = 0
      running_loss = 0
      running_accuracy = 0
      total = 0

      for epoch in range(epochs):
        print('epoch : {}/{}'.format(epoch+1, epochs))

        for images, labels in train_loader:
          images, labels = images.to(device), labels.to(device)

          optimizer.zero_grad()

          outputs = model(images)
          loss = criterion(outputs, labels)

          _, predictions = torch.max(outputs, dim=1)

          loss.backward()
          optimizer.step()

          running_loss += loss.item()

          running_accuracy += torch.sum(predictions == labels.data)
          


        epoch_loss = running_loss / len(train_dataset)
        epoch_accuracy = running_accuracy / len(train_dataset)

        print('Loss:{:.4f} , Accuracy : {:.4f} '.format(epoch_loss, epoch_accuracy))

      return model

【问题讨论】:

  • 请将代码添加为格式化文本,而不是图像
  • 您的标签是单热编码还是索引?
  • @couka 谢谢你的建议,我不知道,因为我是新手。
  • @Ivan Thnak 你!它有帮助。

标签: pytorch data-science image-classification


【解决方案1】:

您可能应该使用torch.argmax 从您的模型输出中获取类预测,而不是使用torch.max

假设您使用索引作为标签。类似以下的内容将为您提供当前批次的平均准确度:

>>> outputs = torch.rand(16, 5)

>>> pred = torch.argmax(outputs, axis=0)
tensor([14, 11, 13, 15,  7])

>>> labels = torch.tensor([14, 6, 13, 5, 8])

>>> accuracy = (pred == labels).float().mean()
tensor(0.4000)

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 2020-07-11
    • 2020-05-23
    • 1970-01-01
    • 2021-05-09
    • 2021-05-18
    • 1970-01-01
    • 2021-11-13
    • 2017-12-22
    相关资源
    最近更新 更多