【机器学习】_02_模型的选择与评估

1 模型验证

模型验证方法如下:

  1. 通过交叉验证得分:model_sleection.cross_val_score(estimator,X)
  2. 对每个输入数据点产生交叉验证估计:model_selection.cross_val_predict(estimator,X)
  3. 计算并绘制模型的学习率曲线:model_selection.learning_curve(estimator,X,y)
  4. 计算并绘制模型的验证曲线:model_selection.validation(estimator,...)
  5. 通过排序评估交叉验证的得分在重要性:model_selection.permutation_test_score(...)

1.1 交叉验证

进行模型验证的一个重要目的是要选出一个最合适的模型,对于监督学习而言,我们希望模型对于未知数据的泛化能力强,所以就需要模型验证这一过程来体现不同的模型对于未知数据的表现效果。

最先我们用训练准确度(用全部数据进行训练和测试)来衡量模型的表现,这种方法会导致模型过拟合;为了解决这一问题,我们将所有数据分成训练集和测试集两部分,我们用训练集进行模型训练,得到的模型再用测试集来衡量模型的预测表现能力,这种度量方式叫测试准确度,这种方式可以有效避免过拟合。

测试准确度的一个缺点是其样本准确度是一个高方差估计(high variance estimate),所以该样本准确度会依赖不同的测试集,其表现效果不尽相同。

交叉验证的基本思想是:将数据集进行一系列分割,生成一组不同的训练测试集,然后分别训练模型并计算测试准确率,最后对结果进行平均处理。这样来有效降低测试准确率的差异。

K折交叉验证步骤:

  1. 将数据集平均分割成K个等份
  2. 使用1份数据作为测试数据,其余作为训练数据
  3. 计算测试准确率
  4. 使用不同的测试集,重复2、3步骤
  5. 对测试准确率做平均,作为对未知数据预测准确率的估计

交叉验证优点:

  1. 交叉验证用于评估模型的预测性能,尤其是训练好的模型在新数据上的表现,可以在一定程度上减小过拟合。
  2. 还可以从有限的数据中获取尽可能多的有效信息。

下面通过一个简单的实例来说明:(iris鸢尾花)

from sklearn import datasets	#自带数据集
from sklearn.model_selection import train_test_split,cross_val_score	#划分数据 交叉验证
from sklearn.neighbors import KNeighborsClassifier  #一个简单的模型,只有K一个参数,类似K-means
import matplotlib.pyplot as plt
iris = datasets.load_iris()		#加载sklearn自带的数据集
X = iris.data 			#这是数据
y = iris.target 		#这是每个数据所对应的标签
train_X,test_X,train_y,test_y = train_test_split(X,y,test_size=1/3,random_state=3)	#这里划分数据以1/3的来划分 训练集训练结果 测试集测试结果
k_range = range(1,31)
cv_scores = []		#用来放每个模型的结果值
for n in k_range:
    knn = KNeighborsClassifier(n)   #knn模型,这里一个超参数可以做预测,当多个超参数时需要使用另一种方法GridSearchCV
    scores = cross_val_score(knn,train_X,train_y,cv=10,scoring='accuracy')  #cv:选择每次测试折数  accuracy:评价指标是准确度,可以省略使用默认值
    cv_scores.append(scores.mean())
plt.plot(k_range,cv_scores)
plt.xlabel('K')
plt.ylabel('Accuracy')		#通过图像选择最好的参数
plt.show()
best_knn = KNeighborsClassifier(n_neighbors=3)	# 选择最优的K=3传入模型
best_knn.fit(train_X,train_y)			#训练模型
print(best_knn.score(test_X,test_y))	#看看评分

交叉验证的作用:

  1. 用于调节参数
  2. 用于模型选择
  3. 用于特征选择

2 调整估计器的超参数

当我们对每一个模型都进行了交叉验证后,就能够选出一个对于当前问题最优的模型。接下来就需要解决第二个问题:对模型调参。在这里我们使用网格搜索(grid search)来对模型选择一套合适的参数。

下面以随机森林的调参为例:

'''
    第三步:调参
    对基于CART的随机森林的调参,主要有:
    1,树的个数
    2,树的最大深度
    3,内部节点最少样本数与叶节点最少样本数
    4,特征个数
    此外,调参过程中选择的误差函数是均值误差,5倍折叠
    '''
    print("----第1步参数调整")
    param_test1 = {'n_estimators': range(90, 151, 5)}
    print(param_test1)
    gsearch1 = GridSearchCV(
        estimator=RandomForestRegressor(min_samples_split=50, min_samples_leaf=10, max_depth=8, max_features='sqrt',
                                        random_state=10), param_grid=param_test1, scoring='neg_mean_squared_error',
        cv=5)
    gsearch1.fit(X, y)
    gsearch1.best_params_, gsearch1.best_score_
    best_n_estimators = gsearch1.best_params_['n_estimators']
    print("best_n_estimators:", best_n_estimators)

    print("----第2步参数调整")
    param_test2 = {'max_depth': range(3, 15), 'min_samples_split': range(10, 101, 10)}
    gsearch2 = GridSearchCV(
        estimator=RandomForestRegressor(n_estimators=best_n_estimators, min_samples_leaf=10, max_features='sqrt',
                                        random_state=10, oob_score=True), param_grid=param_test2,
        scoring='neg_mean_squared_error', cv=5)
    gsearch2.fit(X, y)
    gsearch2.best_params_, gsearch2.best_score_
    best_max_depth = gsearch2.best_params_['max_depth']
    best_min_samples_split = gsearch2.best_params_['min_samples_split']
    print("best_max_depth:", best_max_depth)
    print("best_min_samples_split:", best_min_samples_split)

    print("----第3步参数调整")
    param_test3 = {'min_samples_leaf': range(50, 70, 2)}
    gsearch3 = GridSearchCV(
        estimator=RandomForestRegressor(n_estimators=best_n_estimators, max_depth=best_max_depth, max_features='sqrt',
                                        min_samples_split=best_min_samples_split, random_state=10, oob_score=True),
        param_grid=param_test3, scoring='neg_mean_squared_error', cv=5)
    gsearch3.fit(X, y)
    gsearch3.best_params_, gsearch3.best_score_
    best_min_samples_leaf = gsearch3.best_params_['min_samples_leaf']
    print("best_min_samples_leaf:", best_min_samples_leaf)

    print("----第4步参数调整")
    numOfFeatures = len(numFeatures)
    mostSelectedFeatures = numOfFeatures / 2
    param_test4 = {'max_features': range(3, numOfFeatures + 1)}
    gsearch4 = GridSearchCV(estimator=RandomForestRegressor(n_estimators=best_n_estimators, max_depth=best_max_depth,
                                                            min_samples_leaf=best_min_samples_leaf,
                                                            min_samples_split=best_min_samples_split, random_state=10,
                                                            oob_score=True), param_grid=param_test4,
                            scoring='neg_mean_squared_error', cv=5)
    gsearch4.fit(X, y)
    gsearch4.best_params_, gsearch4.best_score_
    best_max_features = gsearch4.best_params_['max_features']
    print("best_max_features:", best_max_features)

    print("----随机森林拟合")
    # 把最优参数全部获取去做随机森林拟合
    cls = RandomForestRegressor(n_estimators=best_n_estimators, max_depth=best_max_depth,
                                min_samples_leaf=best_min_samples_leaf, min_samples_split=best_min_samples_split,
                                max_features=best_max_features, random_state=10, oob_score=True)
    cls.fit(X, y)

3 模型评估方法

有 3 种不同的 API 用于评估模型预测的质量:

【1】Estimator score method(估计器得分的方法): Estimators(估计器)有一个 score(得分) 方法,为其解决的问题提供了默认的 evaluation criterion (评估标准)。 在这个页面上没有相关讨论,但是在每个 estimator (估计器)的文档中会有相关的讨论。

score(self,X,y,y_true)函数在内部会调用predict函数获得预测响应y_predict,然后与传人的真实响应进行比较,计算得分

使用estimator的score函数来苹果模型的性能,默认情况下

分类器对应于准确率:sklearn.metrics.accuracy_score

回归器对应于R2得分:sklearn.metrics.r2_score

【2】Scoring parameter(评分参数): Model-evaluation tools (模型评估工具)使用 cross-validation (如 model_selection.cross_val_score 和 model_selection.GridSearchCV) 依靠 internal scoring strategy (内部 scoring(得分) 策略)。这在 scoring 参数: 定义模型评估规则 部分讨论。

上面的两个模型选择工具中都有一个参数“scoring”,该参数用来指定在进行网格搜索或计算交叉验证得分的时候,用什么标砖度量“estimator”的预测性能。默认情况下,该参数为“None”就表示“GridSearchCV”与“cross_val_score”都会去调用“estimator”自己的“score”函数,我们也可以为“scoring”参数指定别的性能度量标准,他必须是一个可调用对象,sklearn.metric不仅为我们提供了一系列预定义的可调用对象,而且好支持自定义评估标准。

”scoring“的可用类型都存放在sklearn.metric.SCORES字典对象中

【3】Metric functions(指标函数): metrics 模块实现了针对特定目的评估预测误差的函数。这些指标在以下部分部分详细介绍 分类指标, 多标签排名指标, 回归指标 和 聚类指标 。

使用sklearn.metric包中的性能度量函数有:

  • 分类器性能指标
  • 回归器性能指标
  • 聚类其性能指标
  • 两两距离测度

总的来说,主要分为以下3类

  • 精度-召回率-F度量:Precision-Recall-F_measures
  • 损失函数:Loss Function
  • 接收机操作曲线:ROC Curves

只限于二分类单标签分类问题的评估指标

  • matthews_corrcoef(y_true,y_pred[],...):计算二元分类中的Matthews相关系数(MCC)
  • precision_recall_curve(y_true,probas_pred):在不同的概率阈值下计算precision-recall点,形成曲线
  • roc_curve(y_true,y_score[,pos_label,...]):计算ROC曲线

可用于二分类多标签分类问题的评估指标

  • average_precision_score(y_true,y_score[,...]) 计算预测得分的平均精度(mAP)
  • roc_auc_score(y_true,y_score[,average,...])计算预测得分的AUC值

可用于多分类问题的评估指标(紫色的可用于多标签分类问题)

  • cohen_kappa_score(y1,y2[,labels,weights])
  • confusion_matrix(y_true,y_pred[,labels,...])
  • hinge_loss(y_true,pred_decision[,labels,...])
  • accuracy_score(y_true,y_pred[,normalize,...])
  • classification_report(y_true,y_pred[,...])
  • f1_score(y_true,y_pres[,labels,...])
  • fbeta_score(y_true,,y_pres,beta[,labels,...])
  • hamming_loss(y_true,y_pres[,labels,...])
  • jaccard_similarity_score(y_true,y_pres[,...])
  • log_loss(y_true,y_pres[,eps,normalize,...])
  •  zero_one_loss(y_true,y_pres[,normalize,...])
  • precision_recall_fsconfe_support(y_true,y_pres)

分类器性能评估指标:

  • 接收机操作曲线Reciever Operating Curves-》可用于二分类问题
  • 解卡德指数(相似性系数)Jaccard similarity coefficient-》可用于多分类问题
  • MCC指标(相关性系数)Matthews correlation coefficient-》可用于二分类问题
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值