Skip to content

Instantly share code, notes, and snippets.

@howard-haowen
Forked from fclesio/get_classification_report.py
Last active May 14, 2021 03:49
Show Gist options
  • Save howard-haowen/1e566405bc7c4bb575eedfbbc19b619a to your computer and use it in GitHub Desktop.
Save howard-haowen/1e566405bc7c4bb575eedfbbc19b619a to your computer and use it in GitHub Desktop.
Scikit Learn metrics to Pandas DataFrame
from sklearn.metrics import classification_report, confusion_matrix
import pandas as pd
def get_df_classification_report(y_test, y_pred, target_names):
'''Source: https://stackoverflow.com/questions/39662398/scikit-learn-output-metrics-classification-report-into-csv-tab-delimited-format'''
report = classification_report(y_test, y_pred, output_dict=True, target_names=target_names)
df = pd.DataFrame(report).transpose()
return df.round(decimals=3)
# example
'''
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['類別1', '類別2', '類別3']
df = get_df_classification_report(y_true, y_pred, target_names)
'''
#source: https://gist.github.com/nickynicolson/202fe765c99af49acb20ea9f77b6255e
def get_df_confusion_matrix(y_true, y_pred, labels):
cm = confusion_matrix(y_true, y_pred)
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]
# example
'''
y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
labels= ["ant", "bird", "cat"]
df = get_df_confusion_matrix(y_true, y_pred, labels)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment