模型评估和参数调优

     本篇文章详细阐述机器学习模型评估和参数调优。将主要围绕两个问题来阐述:

  1. “知其所以然”:当你选择的一个机器学习模型运行时,你要知道它是如何工作的;
  2. “青出于蓝”:更进一步,你得知道如何让此机器学习模型工作的更优。
模型评估的方法

      一般情况来说,F1评分或者R平方(R-Squared value)等数值评分可以告诉我们训练的机器学习模型的好坏。也有其它许多度量方式来评估拟合模型。

      你应该猜出来,我将提出使用可视化的方法结合数值评分来更直观的评判机器学习模型。接下来的几个部分将分享一些有用的工具。

     首先想声明的,单单一个评分或者一条线,是无法完全评估一个机器学习模型。偏离真实场景来评估机器学习模型(’good’ or ‘bad’)都是“耍流氓”。某个机器学习模型若可“驾驭”小样本数据集生成最多预测模型(即,命中更多预测数据集)。如果一个拟合模型比其它拟合过的模型形式或者你昨天的预测模型能够得到更好的结果,那即是好(’good’)。

     下面是一些标准指标: confusion_matrix,mean_squared_error, r2_score,这些可以用来评判分类器或者回归的好坏。表格中给出的是Scikit-Learn中的函数以及描述:

评估分类模型:

指标描述Scikit-learn函数
Precision精准度from sklearn.metrics import precision_score
Recall召回率from sklearn.metrics import recall_score
F1F1值from sklearn.metrics import f1_score
Confusion Matrix混淆矩阵from sklearn.metrics import confusion_matrix
ROCROC曲线from sklearn.metrics import roc
AUCROC曲线下的面积from sklearn.metrics import auc

评估回归模型:

指标描述Scikit-learn函数
Mean Square Error (MSE, RMSE)平均方差from sklearn.metrics import mean_squared_error
Absolute Error (MAE, RAE)绝对误差from sklearn.metrics import mean_absolute_error, median_absolute_error
R-SquaredR平方值from sklearn.metrics import r2_score

    下面开始使用Scikit-Learn的可视化工具来更直观的展现模型的好坏。

评估分类模型

    我们评估分类器是判断预测值时否很好的与实际标记值相匹配。正确的鉴别出正样本(True Positives)或者负样本(True Negatives)都是True。同理,错误的判断正样本(False Positive,即一类错误)或者负样本(False Negative,即二类错误)。

注意:True和False是对于评价预测结果而言,也就是评价预测结果是正确的(True)还是错误的(False)。而Positive和Negative则是样本分类的标记。

    通常,我们希望通过一些参数来告知模型评估如何。为此,我们使用混淆矩阵。

混淆矩阵

    幸运的是,Scikit-Learn提供内建函数(sklearn.metrics.confusion_matrix)来计算混淆矩阵。输入数据集实际值和模型预测值作为参数,输出即为混淆矩阵,结果类似这样:


        
        
  1. [ [ 1238 19 ] # True Positives = 1238, False Negatives = 19
  2. [ 2 370 ] ] # False Positives = 2, True Negatives = 370
分类报告

     分类报告除了包括混淆矩阵,也增加了其它优势,比如,混淆矩阵会标示样例是否被正确鉴别,同时也提供precision,recall和 F1 值三种评估指标。


        
        
  1. from sklearn. metrics import classification_report
  2. print (classification_report (y_true , y_pred , target_names =target_names ) )

更进一步,可以对Scikit-Learn的内建函数做些加强,比如,使用带颜色区分的热力图,它将帮助我们的眼睛更容易的辨别预测成功(橘黄色)和失败(灰色)。代码如下:


        
        
  1. from matplotlib import colors
  2. from matplotlib. colors import ListedColormap
  3. ddl_heat = [ '#DBDBDB' , '#DCD5CC' , '#DCCEBE' , '#DDC8AF' , '#DEC2A0' , '#DEBB91' ,\
  4. '#DFB583' , '#DFAE74' , '#E0A865' , '#E1A256' , '#E19B48' , '#E29539' ]
  5. ddlheatmap = colors. ListedColormap (ddl_heat )
  6. def plot_classification_report ( cr , title = None , cmap = ddlheatmap ) :
  7. title = title or 'Classification report'
  8. lines = cr. split ( '\n' )
  9. classes = [ ]
  10. matrix = [ ]
  11. for line in lines [ 2: ( len (lines ) - 3 ) ]:
  12. s = line. split ( )
  13. classes. append (s [ 0 ] )
  14. value = [ float (x ) for x in s [ 1: len (s ) - 1 ] ]
  15. matrix. append (value )
  16. fig , ax = plt. subplots ( 1 )
  17. for column in range ( len (matrix ) 1 ):
  18. for row in range ( len (classes ) ):
  19. txt = matrix [row ] [column ]
  20. ax. text (column ,row ,matrix [row ] [column ] ,va = 'center' ,ha = 'center' )
  21. fig = plt. imshow (matrix , interpolation = 'nearest' , cmap =cmap )
  22. plt. title (title )
  23. plt. colorbar ( )
  24. x_tick_marks = np. arange ( len (classes ) 1 )
  25. y_tick_marks = np. arange ( len (classes ) )
  26. plt. xticks (x_tick_marks , [ 'precision' , 'recall' , 'f1-score' ] , rotation = 45 )
  27. plt. yticks (y_tick_marks , classes )
  28. plt. ylabel ( 'Classes' )
  29. plt. xlabel ( 'Measures' )
  30. plt. show ( )
  31. cr = classification_report (y_true , y_pred )
  32. plot_classification_report (cr )

看起来挺容易,对不?发现分类热力图的另外一个好处,它可以让我们看出一类错误 VS 二类错误。但有一个缺陷,它并不能垮模型进行比较,而这对评估拟合模型是相当重要的。因为这个原因,接下来将使用第二篇文章中的classify和regress代码。

下面的get_preds函数将输出一个实际标记值和预测值的二元组,这个二元组将会使得后续的跨模型的可视化比较变得容易:


        
        
  1. def get_preds ( attributes , targets , model ) :
  2. '''
  3. Executes classification or regression using the specified model
  4. and returns expected and predicted values.
  5. Useful for comparison plotting!
  6. '''
  7. splits = cv. train_test_split (attributes , targets , test_size = 0.2 )
  8. X_train , X_test , y_train , y_test = splits
  9. model. fit (X_train , y_train )
  10. y_true = y_test
  11. y_pred = model. predict (X_test )
  12. return (y_true ,y_pred )
ROC曲线

另一种评估分类模型的方法是ROC(Receiver Operating Characteristic)曲线。我们能从Scikit-Learn 指标模块中import roc_curve,计算 true positive率和false positive 率的数值。我们也可以画出ROC曲线来权衡模型的敏感性和特异性。

下面的代码将画出ROC,Y轴代表true positive率,X轴代表false positive 率。同时,我们也可以增加同时比较两种不同的拟合模型,这里看到的是 KNeighborsClassifier 分类器远胜 LinearSVC 分类器:


        
        
  1. def roc_compare_two ( y , yhats , models ) :
  2. f , (ax1 , ax2 ) = plt. subplots ( 1 , 2 , sharey = True )
  3. for yhat , m , ax in ( (yhats [ 0 ] , models [ 0 ] , ax1 ) , (yhats [ 1 ] , models [ 1 ] , ax2 ) ):
  4. false_positive_rate , true_positive_rate , thresholds = roc_curve (y ,yhat )
  5. roc_auc = auc (false_positive_rate , true_positive_rate )
  6. ax. set_title ( 'ROC for %s' % m )
  7. ax. plot (false_positive_rate , true_positive_rate , \
  8. c = '#2B94E9' , label = 'AUC = %0.2f'% roc_auc )
  9. ax. legend (loc = 'lower right' )
  10. ax. plot ( [ 0 , 1 ] , [ 0 , 1 ] , 'm--' ,c = '#666666' )
  11. plt. xlim ( [ 0 , 1 ] )
  12. plt. ylim ( [ 0 , 1.1 ] )
  13. plt. show ( )
  14. y_true_svc , y_pred_svc = get_preds (stdfeatures , labels , LinearSVC ( ) )
  15. y_true_knn , y_pred_knn = get_preds (stdfeatures , labels , KNeighborsClassifier ( ) )
  16. actuals = np. array ( [y_true_svc ,y_true_knn ] )
  17. predictions = np. array ( [y_pred_svc ,y_pred_knn ] )
  18. models = [ 'LinearSVC' , 'KNeighborsClassifier' ]
  19. roc_compare_two (actuals , predictions , models )

在ROC空间,ROC曲线越凸向左上方向效果越好;越靠近对角线,分类器越趋向于随机分类器。

同时,我们也会计算曲线下的面积(AUC),可以结合上图。如果AUC的值达到0.80,那说明分类器分类非常准确;如果AUC值在0.60~0.80之间,那分类器还算好,但是我们调调参数可能会得到更好的性能;如果AUC值小于0.60,那就惨不忍睹了,你得好好分析下咯。

评估回归模型

对于混凝土数据集试验一些不同的机器学习模型,然后评判哪种更好。在第二篇文章中,我们使用的平均方差和 R 平方值,比如:


        
        
  1. Mean squared error = 116.268
  2. R2 score = 0.606

这些数值是有用的,特别是对不同的拟合模型比较平均方差和 R 平方值。但是,这是不够的,它不能告诉我们为什么一个模型远胜于另外一个;也不能告诉我们如何对模型调参数提高评分。接下来,我们将看到两种可视化的评估技术来帮助诊断模型有效性:预测错误曲线 和 残差曲线。

预测错误曲线

为了知道我们的模型预测值与期望值到底有多接近,我们将拿混凝土数据集(混凝土强度)做例子,画出其期望值和模型预测值曲线。下面是不同回归模型的错误曲线:Ridge, SVR 和RANSACRegressor。


        
        
  1. def error_compare_three ( mods , X , y ) :
  2. f , (ax1 , ax2 , ax3 ) = plt. subplots ( 3 , sharex = True , sharey = True )
  3. for mod , ax in ( (mods [ 0 ] , ax1 ) , (mods [ 1 ] , ax2 ) , (mods [ 2 ] , ax3 ) ):
  4. predicted = cv. cross_val_predict (mod [ 0 ] , X , y , cv = 12 )
  5. ax. scatter (y , predicted , c = '#F2BE2C' )
  6. ax. set_title ( 'Prediction Error for %s' % mod [ 1 ] )
  7. ax. plot ( [y. min ( ) , y. max ( ) ] , [y. min ( ) , y. max ( ) ] , 'k--' , lw = 4 , c = '#2B94E9' )
  8. ax. set_ylabel ( 'Predicted' )
  9. plt. xlabel ( 'Measured' )
  10. plt. show ( )
  11. models = np. array ( [ (Ridge ( ) , 'Ridge' ) , (SVR ( ) , 'SVR' ) , (RANSACRegressor ( ) , 'RANSAC' ) ] )
  12. error_compare_three (models , features , labels )

从这里可以很清晰的看出预测值和期望值的关系。同时也发现线性回归模型效果好。

残差曲线

残差是数据集每个实例的实际标记值和预测值之间的差值。通过画出一系列实例的残差,可以帮助我们检测它们是否随机错误。


        
        
  1. def resids_compare_three ( mods , X , y ) :
  2. f , (ax1 , ax2 , ax3 ) = plt. subplots ( 3 , sharex = True , sharey = True )
  3. plt. title ( 'Plotting residuals using training (blue) and test (green) data' )
  4. for m , ax in ( (mods [ 0 ] , ax1 ) , (mods [ 1 ] , ax2 ) , (mods [ 2 ] , ax3 ) ):
  5. for feature in list (X ):
  6. splits = cv. train_test_split (X [ [feature ] ] , y , test_size = 0.2 )
  7. X_tn , X_tt , y_tn , y_tt = splits
  8. m [ 0 ]. fit (X_tn , y_tn )
  9. ax. scatter (m [ 0 ]. predict (X_tn ) ,m [ 0 ]. predict (X_tn )-y_tn ,c = '#2B94E9' ,s = 40 ,alpha = 0.5 )
  10. ax. scatter (m [ 0 ]. predict (X_tt ) , m [ 0 ]. predict (X_tt )-y_tt ,c = '#94BA65' ,s = 40 )
  11. ax. hlines (y = 0 , xmin = 0 , xmax = 100 )
  12. ax. set_title (m [ 1 ] )
  13. ax. set_ylabel ( 'Residuals' )
  14. plt. xlim ( [ 20 , 70 ] ) # Adjust according to your dataset
  15. plt. ylim ( [ - 50 , 50 ] )
  16. plt. show ( )
  17. models = np. array ( [ (Ridge ( ) , 'Ridge' ) , (LinearRegression ( ) , 'Linear Regression' ) , (SVR ( ) , 'SVR' ) ] )
  18. resids_compare_three (models , features , labels )

Bias VS Variance

每种评估器都有是有利有弊。

首先 Error = Bias Variance。Error反映的是整个模型的准确度,Bias反映的是模型在样本上的输出与真实值之间的误差,即模型本身的精准度,Variance反映的是模型每一次输出结果与模型输出期望之间的误差,即模型的稳定性。

机器学习可视化调参

在文章开篇,我们提出了两个问题:我们如何知道一个机器学习模型可以工作?我们如何让这个模型工作(运行)的更好?

接下来,我们将回答第二个问题。如果你有注意,我们用的模型都是使用Scikit-Learn 默认的参数。对于我们的大部分拟合模型来讲,评分已经相当好了。但有时并没有那么幸运,这时我们就得自己调参数。

可视化训练和验证模型

如何选择最好的模型参数呢?一种方法是,用单一参数的不同值去验证一个模型的评估分数。让我们拿SVC 分类器来试验,通过调不同的gama值来画出训练值和测试纸的曲线。

我们的关注点是训练值和测试值都高的点。如果两者都低,那是欠拟合(underfit);如果训练值高但是测试值低,那说明是过拟合(overfit)。

下面的代码画出来的曲线是拿信用卡数据集来做例子,这里用的 6折交叉验证。


        
        
  1. def plot_val_curve ( features , labels , model ) :
  2. p_range = np. logspace ( - 5 , 5 , 5 )
  3. train_scores , test_scores = validation_curve (
  4. model , features , labels , param_name = 'gamma' , param_range =p_range ,
  5. cv = 6 , scoring = 'accuracy' , n_jobs = 1
  6. )
  7. train_scores_mean = np. mean (train_scores , axis = 1 )
  8. train_scores_std = np. std (train_scores , axis = 1 )
  9. test_scores_mean = np. mean (test_scores , axis = 1 )
  10. test_scores_std = np. std (test_scores , axis = 1 )
  11. plt. title ( 'Validation Curve' )
  12. plt. xlabel ( '$\gamma$' )
  13. plt. ylabel ( 'Score' )
  14. plt. semilogx (p_range , train_scores_mean , label = 'Training score' , color = '#E29539' )
  15. plt. semilogx (p_range , test_scores_mean , label = 'Cross-validation score' , color = '#94BA65' )
  16. plt. legend (loc = 'best' )
  17. plt. show ( )
  18. X = scale (credit [ [ 'limit' , 'sex' , 'edu' , 'married' , 'age' , 'apr_delay' ] ] )
  19. y = credit [ 'default' ]
  20. plot_val_curve (X , y , SVC ( ) )

Grid Search

对于超参数调优,大部分人使用的grid search。Grid search是一种暴力调参方法,即遍历所有可能的参数值。

对于信用卡数据集使用 SVC模型,我们通过试验不同内核系数gama来提高预测准确性:


        
        
  1. from sklearn. grid_search import GridSearchCV
  2. def blind_gridsearch ( model , X , y ) :
  3. C_range = np. logspace ( - 2 , 10 , 5 )
  4. gamma_range = np. logspace ( - 5 , 5 , 5 )
  5. param_grid = dict (gamma =gamma_range , C =C_range )
  6. grid = GridSearchCV (SVC ( ) , param_grid =param_grid )
  7. grid. fit (X , y )
  8. print (
  9. 'The best parameters are {} with a score of {:0.2f}.'. format (
  10. grid. best_params_ , grid. best_score_
  11. )
  12. )
  13. features = credit [ [ 'limit' , 'sex' , 'edu' , 'married' , 'age' , 'apr_delay' ] ]
  14. labels = credit [ 'default' ]
  15. blind_gridsearch (SVC ( ) , features , labels )

但是,grid search需要我们理解哪些参数是合适的,参数的意义,参数是如何影响模型的以及参数的合理的搜索范围来初始化搜索。

这里,我们使用 visual_gridsearch 代替 blind_gridsearch 函数:


        
        
  1. def visual_gridsearch ( model , X , y ) :
  2. C_range = np. logspace ( - 2 , 10 , 5 )
  3. gamma_range = np. logspace ( - 5 , 5 , 5 )
  4. param_grid = dict (gamma =gamma_range , C =C_range )
  5. grid = GridSearchCV (SVC ( ) , param_grid =param_grid )
  6. grid. fit (X , y )
  7. scores = [x [ 1 ] for x in grid. grid_scores_ ]
  8. scores = np. array (scores ). reshape ( len (C_range ) , len (gamma_range ) )
  9. plt. figure (figsize = ( 8 , 6 ) )
  10. plt. subplots_adjust (left = .2 , right = 0.95 , bottom = 0.15 , top = 0.95 )
  11. plt. imshow (scores , interpolation = 'nearest' , cmap =ddlheatmap )
  12. plt. xlabel ( 'gamma' )
  13. plt. ylabel ( 'C' )
  14. plt. colorbar ( )
  15. plt. xticks (np. arange ( len (gamma_range ) ) , gamma_range , rotation = 45 )
  16. plt. yticks (np. arange ( len (C_range ) ) , C_range )
  17. plt. title (
  18. "The best parameters are {} with a score of {:0.2f}.". format (
  19. grid. best_params_ , grid. best_score_ )
  20. )
  21. plt. show ( )
  22. visual_gridsearch (SVC ( ) , features , labels )

visual_gridsearch 的方法可以帮助我们理解不同的模型参数下的精确值。但是超参数调优的路程很长,好些人为此研究了几十年。







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值