簡體   English   中英

Sci-kit 學習如何為混淆矩陣打印標簽?

[英]Sci-kit learn how to print labels for confusion matrix?

所以我正在使用sci-kit學習對一些數據進行分類。 我有 13 個不同的類值/分類來對數據進行分類。 現在我已經能夠使用交叉驗證並打印混淆矩陣。 但是,它只顯示沒有類標簽的 TP 和 FP 等,所以我不知道哪個類是什么。 下面是我的代碼和我的輸出:

def classify_data(df, feature_cols, file):
    nbr_folds = 5
    RANDOM_STATE = 0
    attributes = df.loc[:, feature_cols]  # Also known as x
    class_label = df['task']  # Class label, also known as y.
    file.write("\nFeatures used: ")
    for feature in feature_cols:
        file.write(feature + ",")
    print("Features used", feature_cols)

    sampler = RandomOverSampler(random_state=RANDOM_STATE)
    print("RandomForest")
    file.write("\nRandomForest")
    rfc = RandomForestClassifier(max_depth=2, random_state=RANDOM_STATE)
    pipeline = make_pipeline(sampler, rfc)
    class_label_predicted = cross_val_predict(pipeline, attributes, class_label, cv=nbr_folds)
    conf_mat = confusion_matrix(class_label, class_label_predicted)
    print(conf_mat)
    accuracy = accuracy_score(class_label, class_label_predicted)
    print("Rows classified: " + str(len(class_label_predicted)))
    print("Accuracy: {0:.3f}%\n".format(accuracy * 100))
    file.write("\nClassifier settings:" + str(pipeline) + "\n")
    file.write("\nRows classified: " + str(len(class_label_predicted)))
    file.write("\nAccuracy: {0:.3f}%\n".format(accuracy * 100))
    file.writelines('\t'.join(str(j) for j in i) + '\n' for i in conf_mat)

#Output
Rows classified: 23504
Accuracy: 17.925%
0   372 46  88  5   73  0   536 44  317 0   200 127
0   501 29  85  0   136 0   655 9   154 0   172 67
0   97  141 78  1   56  0   336 37  429 0   435 198
0   135 74  416 5   37  0   507 19  323 0   128 164
0   247 72  145 12  64  0   424 21  296 0   304 223
0   190 41  36  0   178 0   984 29  196 0   111 43
0   218 13  71  7   52  0   917 139 177 0   111 103
0   215 30  84  3   71  0   1175    11  55  0   102 62
0   257 55  156 1   13  0   322 184 463 0   197 160
0   188 36  104 2   34  0   313 99  827 0   69  136
0   281 80  111 22  16  0   494 19  261 0   313 211
0   207 66  87  18  58  0   489 23  157 0   464 239
0   113 114 44  6   51  0   389 30  408 0   338 315

如您所見,您無法真正知道哪個列是什么,並且打印也“未對齊”,因此很難理解。

有沒有辦法打印標簽?

doc ,似乎沒有這樣的選項來打印混淆矩陣的行和列標簽。 但是,您可以使用參數labels=...指定標簽順序labels=...

例子:

from sklearn.metrics import confusion_matrix

y_true = ['yes','yes','yes','no','no','no']
y_pred = ['yes','no','no','no','no','no']
print(confusion_matrix(y_true, y_pred))
# Output:
# [[3 0]
#  [2 1]]
print(confusion_matrix(y_true, y_pred, labels=['yes', 'no']))
# Output:
# [[1 2]
#  [0 3]]

如果要打印帶有標簽的混淆矩陣,可以嘗試使用pandas並設置DataFrameindexcolumns

import pandas as pd
cmtx = pd.DataFrame(
    confusion_matrix(y_true, y_pred, labels=['yes', 'no']), 
    index=['true:yes', 'true:no'], 
    columns=['pred:yes', 'pred:no']
)
print(cmtx)
# Output:
#           pred:yes  pred:no
# true:yes         1        2
# true:no          0        3

或者

unique_label = np.unique([y_true, y_pred])
cmtx = pd.DataFrame(
    confusion_matrix(y_true, y_pred, labels=unique_label), 
    index=['true:{:}'.format(x) for x in unique_label], 
    columns=['pred:{:}'.format(x) for x in unique_label]
)
print(cmtx)
# Output:
#           pred:no  pred:yes
# true:no         3         0
# true:yes        2         1

確保您標記混淆矩陣行和列的方式與 sklearn 對類進行編碼的方式完全一致,這一點很重要。 可以使用分類器的 .classes_ 屬性揭示標簽的真實順序。 您可以使用下面的代碼來准備混淆矩陣數據框。

labels = rfc.classes_
conf_df = pd.DataFrame(confusion_matrix(class_label, class_label_predicted, columns=labels, index=labels))
conf_df.index.name = 'True labels'

要注意的第二件事是您的分類器不能很好地預測標簽。 正確預測的標簽數量顯示在混淆矩陣的主對角線上。 您在矩陣中有非零值,並且根本沒有預測某些類 - 列都為零。 使用默認參數運行分類器然后嘗試優化它們可能是個好主意。

看起來您的數據有 13 個不同的類,這就是為什么您的混淆矩陣有 13 行和 13 列。 此外,您的類沒有以任何方式標記,只是我所看到的整數。

如果不是這種情況,並且您的訓練數據具有實際標簽,您可以將唯一標簽列表傳遞給混淆_矩陣

conf_mat = confusion_matrix(class_label, class_label_predicted, df['task'].unique())

由於混淆矩陣只是一個 numpy 矩陣,它不包含任何列信息。 您可以做的是將矩陣轉換為數據框,然后打印此數據框。

import pandas as pd
import numpy as np

def cm2df(cm, labels):
    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]

cm = np.arange(9).reshape((3, 3))
df = cm2df(cm, ["a", "b", "c"])
print(df)

代碼片段來自https://gist.github.com/nickynicolson/202fe765c99af49acb20ea9f77b6255e

輸出:

   a  b  c
a  0  1  2
b  3  4  5
c  6  7  8

另一種更好的方法是在 Pandas 中使用交叉表函數。

pd.crosstab(y_true, y_pred, rownames=['True'], colnames=['Predicted'], margins=True)。

或者

pd.crosstab(le.inverse_transform(y_true), le.inverse_transform(y_pred),rownames=['True'], colnames=['Predicted'], margins=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM