分类报告中的属性错误

AttributeError in Classification report

问题是我想使用分类报告输出 precisio、recall 和 f1-score。但是当我 运行 下面的代码时,会发生该错误。我该如何修复 AttributeError?

print(classification_report(test.targets.cpu().numpy(),
  File "C:\Users\Admin\PycharmProjects\ImageRotation\venv\lib\site-packages\torch\utils\data\dataset.py", line 83, in __getattr__
    raise AttributeError
AttributeError

这是我从我的目录加载数据的地方。

data_loader = ImageFolder(data_dir,transform = transformer)


lab = data_loader.classes
num_classes = int(len(lab))
print("Number of Classes: ", num_classes)

print("The classes are as follows : \n",data_loader.classes)

batch_size = 128
train_size = int(len(data_loader) * 0.8)
test_size = len(data_loader) - train_size

train,test = random_split(data_loader,[train_size,test_size])


train_size = int(len(train) * 0.8)
val_size = len(train) - train_size
train_data, val_data = random_split(train,[train_size,val_size])
#load the train and validation into batches.
print(f"Length of Train Data : {len(train_data)}")
print(f"Length of Validation Data : {len(val_data)}")
print(f"Length of Test Data : {len(test)}")

train_dl = DataLoader(train_data, batch_size, shuffle = True)
val_dl = DataLoader(val_data, batch_size*2)
test_dl = DataLoader(test, batch_size, shuffle=True)

model.evaL() 代码

with torch.no_grad():
    # set the model in evaluation mode
    model.eval()

    # initialize a list to store our predictions
    preds = []
    # loop over the test set
    for (x, y) in test_dl:
        # send the input to the device
        x = x.to(device)
        # make the predictions and add them to the list
        pred = model(x)
        preds.extend(pred.argmax(axis=1).cpu().numpy())
# generate a classification report
print(classification_report(test.targets.cpu().numpy(),
                            np.array(preds), target_names=test.classes))

看起来,ImageFolder 是您的数据集对象,但它不是从 torch.utils.data.Datasets 继承的。
torch Dataloader 尝试在您的 Dataset 对象中调用 __getitem__ 方法,但由于它不是 torch.utils.data.Dataset 对象,因此它没有函数,这导致 AttributeError 现在您得到.
ImageFolder 转换为 torch 火炬数据集。有关图书馆的更多详细信息:torch doc 实际实现:ast_dataloader
此外,您可以使用冻结模型 [无需反向传播] 来加速推理过程。

   with torch.no_grad():
        # make the predictions and add them to the list
        pred = model(x)

更新> 样本火炬数据集:

from torch.utils.data import Dataset
class Dataset_train(Dataset):
    def __init__(self, list_IDs, labels, base_dir):
        """self.list_IDs    : list of strings (each string: utt key),
           self.labels      : dictionary (key: utt key, value: label integer)"""
        self.list_IDs = list_IDs
        self.labels = labels
        self.base_dir = base_dir

    def __len__(self):
        return len(self.list_IDs)

    def __getitem__(self, index):
        key = self.list_IDs[index]
        X, _ = get_sample(f"{self.base_dir}/{key}", self.noises)
        y = self.labels[index]
        return X, y

[注意] get_sample.wav 文件读取的自定义构建函数。你可以用任何功能替换它。
torch example-1
torch example-2
medium example