分类报告中的 AttributeError
pytorch 517
原文标题 :AttributeError in Classification report
问题是我想使用分类报告输出精确度、召回率和 f1 分数。但是当我在代码下面运行时,就会发生该错误。如何修复 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() code
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))
回复
我来回复-
nipun 评论
看来,
ImageFolder
是您的数据集对象,但不是从torch.utils.data.Datasets
继承的。
torch Dataloader 尝试在您的 Dataset 对象中调用__getitem__
方法,但由于它不是torch.utils.data.Dataset
对象,它没有功能,因此导致AttributeError
现在您正在获取。
将ImageFolder
转换为 Torch 数据集。有关更多库详细信息:torch docPractical implemtation: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
文件读取的自定义构建函数。你可以用任何功能替换它。
火炬示例-1
火炬示例-2
中等例子2年前