下面代碼是我總結的針對二分類問題的預測結果分析工具函數。
代碼中有詳細的文檔說明。所以可以直接看代碼。
# -*- coding:utf-8 -*-from __future__ import print_functionfrom __future__ import divisionimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.metrics import roc_curve, aucfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import f1_score"""Model assessment tools."""def print_confusion_matrix(y_true, y_pred): """列印分類混淆矩陣。 Args: y_true: 真實類別。 y_pred: 預測類別。 """ labels = list(set(y_true)) conf_mat = confusion_matrix(y_true, y_pred, labels=labels) print("confusion_matrix(left labels: y_true, up labels: y_pred):") out = "labels\t" for i in range(len(labels)): out += (str(labels[i]) + "\t") print(out) for i in range(len(conf_mat)): out = (str(labels[i]) + "\t") for j in range(len(conf_mat[i])): out += (str(conf_mat[i][j]) + '\t') print(out) return conf_mat
輸出樣本:
confusion_matrix(left labels: y_true, up labels: y_pred):labels 0 1 0 0 14627 1 0 93
def get_auc(y_true, y_pred_pos_prob, plot_ROC=False): """計算 AUC 值。 Args: y_true: 真實標籤,如 [0, 1, 1, 1, 0] y_pred_pos_prob: 預測每個樣本為 positive 的機率。 plot_ROC: 是否繪製 ROC 曲線。 Returns: roc_auc: AUC 值. fpr, tpr, thresholds: see roc_curve. """ fpr, tpr, thresholds = roc_curve(y_true, y_pred_pos_prob) roc_auc = auc(fpr, tpr) # auc 值 if plot_ROC: plt.plot(fpr, tpr, '-*', lw=1, label='auc=%g' % roc_auc) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() return roc_auc, fpr, tpr, thresholds
輸出樣本:
ROC 曲線
def evaluate(y_true, y_pred): """二分類預測結果評估。 Args: y_true: list, 真實標籤,如 [1, 0, 0, 1] y_pred: list,預測結果,如 [1, 1, 0, 1] Returns: 返回正類別的評價指標。 p: 預測為正類別的準確率: p = tp / (tp + fp) r: 預測為正類別的召回率: r = tp / (tp + fn) f1: 預測為正類別的 f1 值: f1 = 2 * p * r / (p + r). """ conf_mat = confusion_matrix(y_true, y_pred) all_p = np.sum(conf_mat[:, 1]) if all_p == 0: p = 1.0 else: p = conf_mat[1, 1] / all_p r = conf_mat[1, 1] / np.sum(conf_mat[1, :]) f1 = f1_score(y_true, y_pred) return p, r, f1def feature_analyze(model, to_print=False, to_plot=True, csv_path=None): """XGBOOST 模型特徵重要性分析。 Args: model: 訓練好的 xgb 模型。 to_print: bool, 是否輸出每個特徵重要性。 to_plot: bool, 是否繪製特徵重要性圖表。 csv_path: str, 儲存到 csv 檔案路徑。 """ feature_score = model.get_fscore() feature_score = sorted(feature_score.items(), key=lambda x: x[1], reverse=True) if to_plot: features = list() scores = list() for (key, value) in feature_score: features.append(key) scores.append(value) plt.barh(range(len(scores)), scores) plt.yticks(range(len(scores)), features) for i in range(len(scores)): plt.text(scores[i] + 0.75, i - 0.25, scores[i]) plt.xlabel('feature socre') plt.title('feature score evaluate') plt.grid() plt.show() fs = [] for (key, value) in feature_score: fs.append("{0},{1}\n".format(key, value)) if to_print: print(''.join(fs)) if csv_path is not None: with open(csv_path, 'w') as f: f.writelines("feature,score\n") f.writelines(fs) return feature_score
輸出樣本:
特徵重要度