11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sklearn.metrics.classification_reportの出力結果をCSVファイルで出力する

Last updated at Posted at 2019-12-28

sklearn.metrics.classification_reportを使ってクラス分類結果をCSVファイルに出力したいという気持ち、あると思います。というわけでCSVファイルを出力するまでのサンプルコードを作成しましたので御覧ください。

サンプルコード

classification_report2csv.py
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report

# https://scikitlearn.org/stable/modules/generated/sklearn.metrics.classification_report.html
y_true = np.array([0, 1, 2, 2, 2])
y_pred = np.array([0, 0, 2, 2, 1])
target_names = ['class 0', 'class 1', 'class 2']

report = classification_report(y_pred=y_pred, y_true=y_true,
                               target_names=target_names, output_dict=True)

# 転置しているのはmetrics名をheaderにするため
report_df = pd.DataFrame(report).T
report_df
"""
	precision	recall	f1-score	support
class 0	0.5	1.000000	0.666667	1.0
class 1	0.0	0.000000	0.000000	1.0
class 2	1.0	0.666667	0.800000	3.0
accuracy	0.6	0.600000	0.600000	0.6
macro avg	0.5	0.555556	0.488889	5.0
weighted avg	0.7	0.600000	0.613333	5.0
"""

# index=Falseにするとラベル名が消えてしまうので注意
report_df.to_csv("report.csv")

pd.read_csv("report.csv", index_col=0)
"""
	precision	recall	f1-score	support
class 0	0.5	1.000000	0.666667	1.0
class 1	0.0	0.000000	0.000000	1.0
class 2	1.0	0.666667	0.800000	3.0
accuracy	0.6	0.600000	0.600000	0.6
macro avg	0.5	0.555556	0.488889	5.0
weighted avg	0.7	0.600000	0.613333	5.0
"""

参考

11
1
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
11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?