機器學習模型評估指標示例

機器學習模型評估指標示例

選擇正確的度量來評估機器學習模型

我們什麼時候評估我們的機器學習模型呢?答案不是隻有一次。通常,我們在實際的數據科學工作流中兩次使用機器學習模型驗證指標:

  1. 模型比較:為您的任務選擇最佳機器學習(ML)模型
  2. 模型改進:調整超參數

為了更清楚地瞭解這兩者之間的區別,讓我通過機器學習(ML)實現的工作流程來解釋。在為任務y設置所有特徵X後,您可以準備多個機器學習模型作為候選。

那麼你怎麼才能最終為你的任務選擇一個呢?是的,這是使用模型驗證度量的第一點。Scikit-learn提供了一些快捷方法來比較模型,比如cross - validation。

在您選擇了一個準確度最好的機器學習模型後,您將跳轉到超參數調優部分,以提高精度和通用性。這裡是您將使用這些度量的第二點。

在本文中,我試圖製作機器學習模型評估指標的總結。

交叉驗證用於模型比較

機器學習模型評估指標示例

訓練/測試拆分和交叉驗證的可視化表示

我們拆分數據的原因和方式的起點是泛化。因為我們構建機器學習模型的目標是使用未來未知數據的真實實現。因此,我們不需要過度擬合過去數據的無用模型。

  • Holdout 方法
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_wine
wine = load_wine()
X, y = wine.data, wine.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
機器學習模型評估指標示例

  • 交叉驗證方法
機器學習模型評估指標示例

K-Folds的視覺表示

# Decision Tree Classifieras for estimator
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state=0)
機器學習模型評估指標示例

cross_val_score:最簡單的編碼方法

我們可以通過參數“cv”來決定數據拆分的數量。通常5被認為是標準拆分數。

# X, y = wine.data, wine.target
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X, y, cv=5)
print(scores) # cv = number of splited data
print(scores.mean())
機器學習模型評估指標示例

機器學習模型評估指標示例

cross_validate:我推薦這個可自定義的

scoring = ['precision_macro', 'recall_macro']
scores = cross_validate(clf, X, y, scoring=scoring, cv=5)
print(scores)
機器學習模型評估指標示例

機器學習模型評估指標示例

迴歸度量

TL; DR:在大多數情況下,我們使用R2或RMSE。

機器學習模型評估指標示例

我將使用Boston House Price數據集。

# Data Preparation
from sklearn.datasets import load_boston
boston = load_boston()
X, y = boston.data, boston.target
# Train data and Test data Splitting
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
機器學習模型評估指標示例

模型1:線性迴歸

reg = LinearRegression()
reg.fit(X_train, y_train)
y_pred1 = reg1.predict(X_test)
機器學習模型評估指標示例

模型2:決策樹迴歸

from sklearn.tree import DecisionTreeRegressor
reg2 = DecisionTreeRegressor(max_depth=3)
reg2.fit(X_train, y_train)
y_pred2 = reg2.predict(X_test)
機器學習模型評估指標示例

現在我們準備評估我們的兩個機器學習模型並選擇一個!

R2:決定係數

from sklearn.metrics import r2_score

r2_score(y_test, y_pred1) # Linear Regression

r2_score(y_test, y_pred2) # Decision Tree Regressor

機器學習模型評估指標示例

機器學習模型評估指標示例

MSE:均方誤差

from sklearn.metrics import mean_squared_error
mean_squared_error(y_test, y_pred)
機器學習模型評估指標示例

>>> 23.873348..

RMSE:均方根誤差

import numpy as np
np.sqrt(mean_squared_error(y_test, y_pred))
機器學習模型評估指標示例

>>> 4.886036..

MAE:平均絕對誤差

reg = LinearRegression()
reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
mean_absolute_error(y_test, y_pred)
機器學習模型評估指標示例

>>> 3.465279..

分類指標

機器學習模型評估指標示例

分類問題:

  1. 一對一分類:例如付費用戶或免費
  2. One vs. Rest分類:例如高級會員或付費或免費

我將使用Iris數據集作為多類分類問題。

# Data Preparation
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
# Train data and Test data Splitting
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
機器學習模型評估指標示例

模型1:SVM

from sklearn.svm import SVC
clf1 = SVC(kernel = 'linear', C = 0.01)
clf1.fit(X_train, y_train)
y_pred1 = clf1.predict(X_test)
機器學習模型評估指標示例

模型2:樸素貝葉斯

from sklearn.naive_bayes import GaussianNB
clf2 = GaussianNB()
clf2.fit(X_train, y_train)
y_pred2 = clf2.predict(X_test)
機器學習模型評估指標示例

現在我們準備評估我們的兩個模型並選擇一個!

1.準確性:

from sklearn.metrics import accuracy_score

accuracy_score(y_test, y_pred1)

accuracy_score(y_test, y_pred2)

機器學習模型評估指標示例

機器學習模型評估指標示例

2.精度:

from sklearn.metrics import precision_score

precision_score(y_test, y_pred1, average=None)

precision_score(y_test, y_pred2, average=None)

機器學習模型評估指標示例

機器學習模型評估指標示例

3.召回或靈敏度:

from sklearn.metrics import recall_score
recall_score(y_test, y_pred2, average=None)
機器學習模型評估指標示例

>>> array([1. , 1. , 0.85714286]) # GNB

4. F分數:

from sklearn.metrics import f1_score
f1_score(y_test, y_pred2, average=None)
機器學習模型評估指標示例

>>> array([1. , 0.9375 , 0.92307692]) # GNB

5.混淆矩陣

from sklearn.metrics import confusion_matrix

confusion_matrix(y_test, y_pred2)

機器學習模型評估指標示例

機器學習模型評估指標示例

機器學習模型評估指標示例

6. ROC

如果你不使用OneVsRest Classifier,它不起作用......

from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
clf = OneVsRestClassifier(LinearSVC(random_state=0))
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
機器學習模型評估指標示例

現在我們將通過ROC Curve進行檢查。

from sklearn.metrics import roc_curve 

fpr, tpr, thresholds = roc_curve(y_test, y_pred, pos_label=2)
fpr, tpr, thresholds
機器學習模型評估指標示例

機器學習模型評估指標示例

7. AUC:曲線下面積

from sklearn.metrics import auc
auc(fpr, tpr)
機器學習模型評估指標示例

>>> 0.913333... # auc

8.多類對數損失

這是一個概率。並且需要使用OneVsRestClassifier。

# clf = OneVsRestClassifier(LinearSVC(random_state=0))
from sklearn.metrics import log_loss
y_pred = clf.predict_proba(X_test) # not .predict()
log_loss(y_test, y_pred)
機器學習模型評估指標示例

>>> 0.09970990582482485

聚類度量

機器學習模型評估指標示例

基本上在真正的聚類任務中,(我的意思是無監督聚類),我們沒有任何方法來測量準確度或精度,因為沒有人知道。

然而,作為分類任務的過程,有時我們使用有監督的聚類來了解數據的特徵。(在實際工作中也是如此。)

因此,我將快速介紹一些監督聚類的指標。

我只使用了Iris數據集中的特徵來解決聚類問題。

from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
機器學習模型評估指標示例

作為聚類問題的代表模型,這次我使用了K-means。

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(X)
y_means = kmeans.predict(X)
機器學習模型評估指標示例

現在,監督聚類的結果是在y_means中。

機器學習模型評估指標示例

同質性得分,Completeness Score,V度量得分

from sklearn.metrics import homogeneity_score, completeness_score, v_measure_score

hg = homogeneity_score(y, y_means)

co = completeness_score(y, y_means)

vm = v_measure_score(y, y_means)

print(hg, co, vm)

機器學習模型評估指標示例

機器學習模型評估指標示例

附加:學習曲線可視化

from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
def plot_learning_curve(clf, title, X, y, ylim=None, cv=None,
n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
clf, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
plt.legend(loc="best")
return plt
title = "Learning Curves (Decision Tree, max_depth=2)"
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
clf = DecisionTreeClassifier(max_depth=2, random_state=0)
plot_learning_curve(clf, title, X, y, ylim=(0.7, 1.01), cv=cv, n_jobs=4)
title = "Learning Curves (SVM, Decision Tree, max_depth=5)"
cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
clf = DecisionTreeClassifier(max_depth=5, random_state=0)
plot_learning_curve(clf, title, X, y, (0.7, 1.01), cv=cv, n_jobs=4)
plt.show()
機器學習模型評估指標示例

機器學習模型評估指標示例


分享到:


相關文章: