我的困惑矩阵工作正常,只是在生成分数时遇到了一些麻烦。一点帮助将大有帮助。我目前收到错误消息。 “张量对象不可调用”。
def get_confused(model_ft):
nb_classes = 120
from sklearn.metrics import precision_recall_fscore_support as score
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for i, (inputs, classes) in enumerate(dataloaders['val']):
inputs = inputs.to(device)
classes = classes.to(device)
outputs = model_ft(inputs)
_, preds = torch.max(outputs, 1)
for t, p in zip(classes.view(-1), preds.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
cm = confusion_matrix(classes, preds)
recall = np.diag(cm) / np.sum(cm, axis = 1)
precision = np.diag(cm) / np.sum(cm, axis = 0)
print(confusion_matrix)
print(confusion_matrix.diag()/confusion_matrix.sum(1))
答案 0 :(得分:1)
问题在于此行。
cm = confusion_matrix(classes, preds)
confusion_matrix
是一个张量,您不能像函数一样调用它。因此Tensor is not callable
。我也不确定您为什么需要此行。相反,我认为您可能想编写cm= confusion_matrix.cpu().data.numpy()
使其成为我认为的numpy数组。从您的代码看来,cm
是np.array
。
答案 1 :(得分:0)
您可以尝试以下代码
def F_score(logit, label, threshold=0.5, beta=2):
prob = torch.sigmoid(logit)
prob = prob > threshold
label = label > threshold
TP = (prob & label).sum().float()
TN = ((~prob) & (~label)).sum().float()
FP = (prob & (~label)).sum().float()
FN = ((~prob) & label).sum().float()
accuracy = (TP+TN)/(TP+TN+FP+FN)
precision = torch.mean(TP / (TP + FP + 1e-12))
recall = torch.mean(TP / (TP + FN + 1e-12))
F2 = (1 + beta**2) * precision * recall / (beta**2 * precision + recall + 1e-12)
return accuracy, precision, recall, F2.mean(0)
将函数称为
accuracy, precision, recall, F1_score = F_score(output.squeeze(), labels.float())
参考:- https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/73246