0
0

ラベル名対応したclassification_report

Posted at

以前に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

image.png
まずこんな感じに名前が反映されます。

df_cm = pd.DataFrame(confusion_matrix(y_test, y_pred))
df_cm.index = index
df_cm.columns = index
df_cm

image.png
混合行列を作る際に必要なインデックスとカラムも関数で作られますのでそのまま使えます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0