机器学习之模型选择与调优

一、交叉验证

什么是交叉验证?

将拿到的训练数据分为训练和验证集。例如将训练数据分成4份,其中一份作为验证集。然后经过4组的测试,每次都更换不同的验证集,即得到4组模型的结果,取平均值作为最终结果,并称为4折交叉验证。

  • 训练集:训练集+验证集
  • 测试集:测试集
    机器学习之模型选择与调优_第1张图片

为什么需要交叉验证?

为了让被评估的模型更加准确可信

二、超参数搜索-网格搜索(Grid Search)

什么是参数搜索?

通常情况下,有很多参数是需要手动指定的(如KNN中的K值),这种叫做超参数。但是手中过程繁杂,所以需要对模型预设几种超参数组合。每种参数组合都采用交叉验证的方式来进行评估。最后选出最优参数组合建立模型。

K值 K=3 k=5 K=7
模型 模型1 模型2 模型3

三、模型选择与调优API

sklearn.model_selection.GriSearchCV(estimator,param_grid=None,cv=None)
  1. 对估计器的指定参数进行详尽搜索
  2. estimator:估计器对象
  3. param_grid:估计其参数,一般使用字典{“n_neighbors”:[1,3,5]}
  4. cv:指定几折交叉验证
  5. fit():输入训练数据
  6. score():准确率
  7. 结果分析:
    最佳参数:best_params_
    最佳结果:best_score_
    最佳估计器:best_estimator_
    交叉验证结果:cv_results_

四、代码实例

这里以使用KNN对莺尾花分类的案例进行调优,参考机器学习之K-近邻算法(KNN),调优后的代码见如下图所示

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV

def knn_iris():
    """
    用KNN算法对莺尾花进行分类
    :return:
    """
    # 1)获取数据
    iris = load_iris()
    # 2)数据划分
    x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,random_state=6)
    # 3)特征工程(标准化)
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test) # 上一步的fit已经计算出来了mean和std,在对x_test进行归一化的时候必须使用和x_train相同的mean和std,故这里只能transform
    # 4)KNN预估器流程
    estimator = KNeighborsClassifier()
    # 加如网格搜索和交叉验证
    #参数准备
    param_dic = {"n_neighbor":[1, 3, 5, 7, 9, 11]}
    estimator = GridSearchCV(estimator,param_grid=param_dic,cv=10)
    estimator.fit(x_train,y_train)
    # 5)模型评估
    """评估方法1:直接比对真实值和预测值"""
    y_predict = estimator.predict(x_test)
    print("y_predict:\n",y_predict)
    print("直接比对真实值和预测值:\n",y_test == y_predict)
    """评估方法2:计算准确率"""
    score = estimator.score(x_test,y_test)# 相当于计算了预估器的准确率,因为这里本来是完全一致的
    print("准确率:\n",score)
    # 最佳参数:best_params_
    print("最佳参数\n",estimator.best_params_)
    # 最佳结果:best_score_
    print("最佳结果\n", estimator.best_score_)
    # 最佳估计器:best_estimator_
    print("最佳估计器\n", estimator.best_estimator_)
    # 交叉验证结果:cv_results_
    print("交叉验证结果\n", estimator.cv_results_)
    return



if __name__ == '__main__':
    knn_iris()

如果报错Invalid parameter xxx for estimator xxx. Check the list of available parameters with xxx
报错原因很明显,是你的estimator的参数不对,比如我给KNeighborsClassifier()了一个参数n_neighbor,但是其实KNeighborsClassifier()的参数是n_neighbors,建议你检查一哈参数是否正确!尤其是针对机器学习中的超参数搜寻的时候,所给字典里面的字段一定要正确!
如下面错误代码

 param_dic = {"n_neighbor":[1, 3, 5, 7, 9, 11]}
 estimator = GridSearchCV(estimator,param_grid=param_dic,cv=10)
 estimator.fit(x_train,y_train)

正确代码应该如下

 param_dic = {"n_neighbors":[1, 3, 5, 7, 9, 11]}
 estimator = GridSearchCV(estimator,param_grid=param_dic,cv=10)
 estimator.fit(x_train,y_train)

完整报错信息

ValueError: Invalid parameter n_neighbor for estimator KNeighborsClassifier(). Check the list of available parameters with `estimator.get_params().keys()`.

修改即可正常运行!!!!

你可能感兴趣的:(机器学习,机器学习,人工智能)