Skip to content

Instantly share code, notes, and snippets.

@nickynicolson
Forked from ClementC/print_cm.py
Last active December 29, 2019 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickynicolson/202fe765c99af49acb20ea9f77b6255e to your computer and use it in GitHub Desktop.
Save nickynicolson/202fe765c99af49acb20ea9f77b6255e to your computer and use it in GitHub Desktop.
Convert scikit-learn confusion matrix to pandas DataFrame
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']]
@CarPiDiem
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment