【发布时间】:2022-01-04 12:14:20
【问题描述】:
我正在使用以下代码来预测我在数据集上的模型输出。
correct = 0
total_predictions = []
actual_labels = []
with torch.no_grad():
for images, labels in testloader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
actual_labels.append(labels)
total_predictions.append(final_pred)
final_pred = torch.FloatTensor(final_pred).to(device)
correct += (predicted == labels).sum().item()
现在要生成整个数据集的混淆矩阵,我尝试将我的预测和测试标签存储在一个列表中,并将其传递给 sklearn 中的confusion_matrix,但失败并出现以下错误:
ValueError: You appear to be using a legacy multi-label data representation. Sequence of sequences are no longer supported; use a binary array or sparse matrix instead.
有人可以帮我计算整个数据集的混淆矩阵吗?
以下代码只计算最后一批:
cf = confusion_matrix(predicted.cpu(), labels.cpu())
Update-1
使用@CutePoison 的模板,我得到了这个。
您似乎在使用旧的多标签数据表示。不再支持序列序列;改用二进制数组或稀疏矩阵 - MultiLabelBinarizer 转换器可以转换为这种格式。
labels={}
labels['healthy_wheat'] = 0
labels['leaf_rust'] = 1
labels['stem_rust'] = 2
def conf_mat(y_true,y_pred,columns,**kwargs):
conf_mat = confusion_matrix(y_true,y_pred,labels = columns,**kwargs)
df = pd.DataFrame(conf_mat,columns = columns, index = columns)
df.columns.name="pred"
df.index.name="true"
return df
conf_mat(actual_labels,total_predictions ,columns =labels,normalize="true")
【问题讨论】:
-
什么失败了?错误信息是什么?
-
@CutePoison 如果我使用 'total_predictions' 和 'actual_labels' 这两个列表,我会收到以下错误:ValueError:您似乎正在使用旧的多标签数据表示。不再支持序列序列;请改用二进制数组或稀疏矩阵。
标签: python conv-neural-network confusion-matrix