-
-
Save nickynicolson/202fe765c99af49acb20ea9f77b6255e to your computer and use it in GitHub Desktop.
Convert scikit-learn confusion matrix to pandas DataFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.metrics import confusion_matrix | |
import pandas as pd | |
def cm2df(cm, labels): | |
df = pd.DataFrame() | |
# rows | |
for i, row_label in enumerate(labels): | |
rowdata={} | |
# columns | |
for j, col_label in enumerate(labels): | |
rowdata[col_label]=cm[i,j] | |
df = df.append(pd.DataFrame.from_dict({row_label:rowdata}, orient='index')) | |
return df[labels] | |
## to use, first generate confusion matrix: | |
#cm = confusion_matrix(expected, predicted) | |
## then convert to pandas DataFrame: | |
#cm_as_df=cm2df(cm,dataset.target_names) | |
## and output: | |
#cm_as_df | |
def precision_recall_fscore_support_metrics2df(prfs, labels): | |
df = pd.DataFrame() | |
for p,r,f,s,label in zip(prfs[0], prfs[1], prfs[2], prfs[3], dataset.target_names): | |
rowdata={} | |
rowdata['precision']=p | |
rowdata['recall']=r | |
rowdata['f1-score']=f | |
rowdata['support']=s | |
df = df.append(pd.DataFrame.from_dict({label:rowdata}, orient='index')) | |
return df[['precision','recall','f1-score','support']] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please show me how you write and constitute the zip function and the call of function "precision_recall_fscore_support_metrics2df" with such parameters as the call of function "cm2df" ?
Thanks in advance