我有一个创建混淆矩阵的函数
def disp_conf_mat(y_act, y_pred, conf_mat_name):data = {'y_Actual': y_act, 'y_Predicted': y_pred }df = pd.DataFrame(data, columns=['y_Actual','y_Predicted'])confusion_matrix = pd.crosstab(df['y_Actual'], df['y_Predicted'], rownames=['Actual'], colnames=['Predicted'])sn.heatmap(confusion_matrix, annot=True)plt.savefig(conf_mat_name)plt.close()
但是如果实际值是[0,1,2,3],而预测值全部为零[0,0,0,0],那么混淆矩阵不会是一个4×4的方形矩阵,而只是一个4×1的矩阵。
Predicted 0Actual 0 11 12 13 1
如何填充那些没有预测值的其他列?(例如,这里是列1,2和3)
回答:
这是预期的行为,如果需要所有可能的值,可以添加DataFrame.reindex
:
confusion_matrix = confusion_matrix.reindex(confusion_matrix.index, axis=1, fill_value=0)