我很难创建一个包含前10个预测错误的图像ID的列表。
import os
import torch
import torchvision
from torch.utils.data import random_split
from torchvision.datasets import ImageFolder
from torchvision.transforms import ToTensor
from torch.utils.data.dataloader import
DataLoader
import torch.nn as nn
import torch.nn.functional as F
batch_size=128
def predict_image(img, model):
# Convert to a batch of 1
xb = to_device(img.unsqueeze(0), device)
# Get predictions from model
yb = model(xb)
# Pick index with highest probability
_, preds = torch.max(yb, dim=1)
# Retrieve the class label
return dataset.classes[preds[0].item()]
def invalid_predictions(n=10):
invalid_ids = []
while invalid_ids
return invalid_ids
# This method should return a list of first
# 10 image ids that the model could not
# predict correctly.
# For example [40, 35, 20, ...]
def invalid_predictions(n=10, images, labels):
invalid_ids = []
image_count = 0
invalid_count = 0
while invalid_count < n:
prediction = predict_image(images[image_count], model)
if prediction != labels[image_count ]:
invalid_ids.append(image_count )
invalid_count +=1
image_count += 1
return invalid_ids