Sklearn - 绘制分类报告给出与基本平均值不同的输出?

sky*_*guy 4 python classification machine-learning scikit-learn

我想利用这个答案如何绘制 scikit 学习分类报告?将 sklearn 分类报告转换为热图。

这一切都与他们的样本报告一起工作,但是我的分类报告看起来略有不同,因此搞砸了功能。

他们的报告(注意平均值/总数):

sampleClassificationReport =             
                   precision    recall  f1-score   support

          Acacia        0.62      1.00      0.76        66
          Blossom       0.93      0.93      0.93        40
          Camellia      0.59      0.97      0.73        67
          Daisy         0.47      0.92      0.62       272
          Echium        1.00      0.16      0.28       413

        avg / total     0.77      0.57      0.49       858
Run Code Online (Sandbox Code Playgroud)

我的报告metrics.classification_report(valid_y, y_pred)

              precision    recall  f1-score   support

           0       1.00      0.18      0.31        11
           1       0.00      0.00      0.00        14
           2       0.00      0.00      0.00        19
           3       0.50      0.77      0.61        66
           4       0.39      0.64      0.49        47
           5       0.00      0.00      0.00        23

    accuracy                           0.46       180
   macro avg       0.32      0.27      0.23       180
weighted avg       0.35      0.46      0.37       180
Run Code Online (Sandbox Code Playgroud)

来自热图链接中选定答案的问题在这里:

for line in lines[2 : (len(lines) - 2)]:
    t = line.strip().split()
    if len(t) < 2: continue
    classes.append(t[0])
    v = [float(x) for x in t[1: len(t) - 1]]
    support.append(int(t[-1]))
    class_names.append(t[0])
    print(v)
    plotMat.append(v)
Run Code Online (Sandbox Code Playgroud)

因为我收到错误:

ValueError:无法将字符串转换为浮点数:'avg'

所以真正的问题是我的分类报告是如何输出的。我可以在这里更改什么以匹配示例?

编辑:我试过的:

df = pd.DataFrame(metrics.classification_report(valid_y, y_pred)).T

df['support'] = df.support.apply(int)

df.style.background_gradient(cmap='viridis',
                             subset=pd.IndexSlice['0':'9', :'f1-score'])
Run Code Online (Sandbox Code Playgroud)

错误:

ValueError:未正确调用 DataFrame 构造函数!

Ven*_*lam 6

随着output_dictparam in的出现,classification_report解析报表不再麻烦。您可以直接使用分类报告的输出来读取为pd.DataFrame. 然后,您可以使用该pd.Style选项来渲染热图。

例子:

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

from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearchCV


X, y = make_classification(n_samples=1000, n_features=30,
                           n_informative=12,
                           n_clusters_per_class=1, n_classes=10,
                           class_sep=2.0, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y)


clf = LogisticRegression(max_iter=1000, random_state=42).fit(X_train, y_train)



df = pd.DataFrame(classification_report(clf.predict(X_test), 
                                        y_test, digits=2,
                                        output_dict=True)).T

df['support'] = df.support.apply(int)

df.style.background_gradient(cmap='viridis',
                             subset=pd.IndexSlice['0':'9', :'f1-score'])
Run Code Online (Sandbox Code Playgroud)