timcompp 2019-03-30
选择正确的度量来评估机器学习模型
我们什么时候评估我们的机器学习模型呢?答案不是只有一次。通常,我们在实际的数据科学工作流中两次使用机器学习模型验证指标:
为了更清楚地了解这两者之间的区别,让我通过机器学习(ML)实现的工作流程来解释。在为任务y设置所有特征X后,您可以准备多个机器学习模型作为候选。
那么你怎么才能最终为你的任务选择一个呢?是的,这是使用模型验证度量的第一点。Scikit-learn提供了一些快捷方法来比较模型,比如cross - validation。
在您选择了一个准确度最好的机器学习模型后,您将跳转到超参数调优部分,以提高精度和通用性。这里是您将使用这些度量的第二点。
在本文中,我试图制作机器学习模型评估指标的总结。
训练/测试拆分和交叉验证的可视化表示
我们拆分数据的原因和方式的起点是泛化。因为我们构建机器学习模型的目标是使用未来未知数据的真实实现。因此,我们不需要过度拟合过去数据的无用模型。
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..
分类问题:
我将使用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()