【機器學習】模型的效能評價指標
阿新 • • 發佈:2019-01-10
混淆矩陣
混淆矩陣:展示學習演算法效能的一種矩陣,一個簡單的方陣,展示一個分類器預測結果(真正,真負,假正,假負)的數量
圖:
使用SKlearn的confusion_matrix方法實現混淆矩陣:
from sklearn.metrics import confusion_matrix
pipe_svc.fit(X_train, y_train)
y_pred = pipe_svc.predict(X_test)
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
print(confmat)
# 繪製混淆矩陣 fig, ax = plt.subplots(figsize=(2.5, 2.5)) ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3) for i in range(confmat.shape[0]): for j in range(confmat.shape[1]): ax.text(x=j, y=i, s=confmat[i, j], va='center', ha='center') plt.xlabel('predicted label') plt.ylabel('true label') plt.tight_layout() # plt.savefig('./figures/confusion_matrix.png', dpi=300) plt.show()
準確率和召回率
預測誤差和準確率投提供了誤分類樣本數量的相關資訊。
誤差(ERR):預測錯樣本的數量與所有被預測樣本數量的比值
準確率(ACC):正確預測樣本的數量與所有被預測樣本數量的比值
對於類別數量不均衡的分類問題來說,真正率與假正率是非常有用的效能指標。
使用SKlearn實現這兩種評分指標:
from sklearn.metrics import precision_score, recall_score, f1_score print('Precision: %.3f' % precision_score(y_true=y_test, y_pred=y_pred)) print('Recall: %.3f' % recall_score(y_true=y_test, y_pred=y_pred)) print('F1: %.3f' % f1_score(y_true=y_test, y_pred=y_pred))
通過make_scorer函式構建評分,則可以以引數的形式提供給GridSearchCV:
from sklearn.metrics import make_scorer, f1_score scorer = make_scorer(f1_score, pos_label=0) c_gamma_range = [0.01, 0.1, 1.0, 10.0] param_grid = [{'clf__C': c_gamma_range, 'clf__kernel': ['linear']}, {'clf__C': c_gamma_range, 'clf__gamma': c_gamma_range, 'clf__kernel': ['rbf'],}] gs = GridSearchCV(estimator=pipe_svc, param_grid=param_grid, scoring=scorer, cv=10, n_jobs=-1) gs = gs.fit(X_train, y_train) print(gs.best_score_) print(gs.best_params_)
ROC曲線:
受試者工作特徵曲線(ROC):基於模型的假正率和真正率等效能指標進行分類模型選擇的有用工具。
假正率和真正率通過移動分類器的分類筏值來計算。
ROC的對角線可以理解為隨機猜測。
如果分類器效能曲線在對角線以下,那麼效能就比隨機猜測還差。
基於ROC可以計算ROC線下區域(AUC)來刻畫分類模型的效能。
使用乳腺癌資料集中的兩個特徵判斷腫瘤是良性還是惡性,並繪製ROC曲線,再次使用邏輯迴歸流水線。
from sklearn.metrics import roc_curve, auc
from scipy import interp
X_train2 = X_train[:, [4, 14]]
cv = StratifiedKFold(y_train, n_folds=3, random_state=1)
fig = plt.figure(figsize=(7, 5))
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
for i, (train, test) in enumerate(cv):
probas = pipe_lr.fit(X_train2[train],
y_train[train]).predict_proba(X_train2[test])
fpr, tpr, thresholds = roc_curve(y_train[test],
probas[:, 1],
pos_label=1)
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
plt.plot(fpr,
tpr,
lw=1,
label='ROC fold %d (area = %0.2f)'
% (i+1, roc_auc))
plt.plot([0, 1],
[0, 1],
linestyle='--',
color=(0.6, 0.6, 0.6),
label='random guessing')
mean_tpr /= len(cv)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
plt.plot(mean_fpr, mean_tpr, 'k--',
label='mean ROC (area = %0.2f)' % mean_auc, lw=2)
plt.plot([0, 0, 1],
[0, 1, 1],
lw=2,
linestyle=':',
color='black',
label='perfect performance')
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 Operator Characteristic')
plt.legend(loc="lower right")
plt.tight_layout()
# plt.savefig('./figures/roc.png', dpi=300)
plt.show()
通過使用scipy中的interp函式利用三個塊資料對 ROC曲線的內插均值進行計算,使用auc函式計算低於ROC曲線區域的面積。
# 計算分類器在單獨測試集上的ROC AUC得分
pipe_svc = pipe_svc.fit(X_train2, y_train)
y_pred2 = pipe_svc.predict(X_test[:, [4, 14]])
from sklearn.metrics import roc_auc_score, accuracy_score
print('ROC AUC: %.3f' % roc_auc_score(y_true=y_test, y_score=y_pred2))
print('Accuracy: %.3f' % accuracy_score(y_true=y_test, y_pred=y_pred2))
多類別分類器的評價標準
Scikit-learn實現了macro(巨集)均值和micro(微)均值方法。
微均值:等同看待每個例項或每次預測時,通過系統的真正,真負,假正,假負來計算
巨集均值:等同看待各個類別,將其用於評估分類器針對最頻繁類標的整體效能。
通過sklearn.metrics模組匯入其他不同的平方引數,利用內建的average引數定義平均方法
使用方法:pre_scorer = make_scorer(score_func=precision_score,
pos_label=1,
greater_is_better=True,
average='micro')