以前にclassification_reportをデータフレーム化する記事を書きました。
今回はこの記事で作った関数をさらに改良したものを作ったので書いてみようと思います。
改善点としてはラベル(文字列)に対応する内容になっています。具体的な内容は使用例をご覧ください。
関数
import pandas as pd
def classification_report_dataframe(y, y_pred, label=None):
rep = classification_report(y, y_pred, output_dict=True)
dst = []
index = []
for col in rep:
if col == "accuracy":
index.append(col)
dst.append(["", "", rep["accuracy"], rep["weighted avg"]["support"]])
elif col != "accuracy":
dst.append([rep[col]["precision"], rep[col]["recall"], rep[col]["f1-score"],rep[col]["support"]])
if label == None:
index.append(col)
elif label != None:
try:
index.append(label[col])
except:
index.append(col)
df_rep = pd.DataFrame(dst)
df_rep.index = index
df_rep.columns = ["precision", "recall", "f1-score", "support"]
return df_rep, index[0:-3]
使用例
ここではScikit-Learnにある実データで顔認識のデータを使います。元々目的変数は数値ですが、他にもその顔の人の名前も載っています。
from sklearn.datasets import fetch_lfw_people
from lightgbm import LGBMClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
faces = fetch_lfw_people(min_faces_per_person=60)
x = faces.data
y = faces.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
model = LGBMClassifier()
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
y_list = list(set(y))
lists = {}
for i in y_list:
lists[str(i)] = faces.target_names[i]
df_rep, index = classification_report_dataframe(y_test, y_pred, label=lists)
df_rep
df_cm = pd.DataFrame(confusion_matrix(y_test, y_pred))
df_cm.index = index
df_cm.columns = index
df_cm