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

交叉验证

将拿到的训练数据,分为训练和验证集。

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

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

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

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

API

sklearn.model_selection.GridSearchCV(estimator,param_grid=None,cv=None)

-对估计器的指定参数进行详尽搜索
-estimator:估计器对象
-param_grid:估计器参数(dict格式) {“n_neighbors”:[1,3,5]}
-cv:指定几折交叉验证
-fit():训练数据
-score():准确率
-结果分析:
	最佳参数:best_params_
	最佳结果:best_score_
	最佳估计器:best_estimator_
	交叉验证结果:cv_results_	

使用演示

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 gscv_knn_demo():
    #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)
    #4.KNN算法预估器
    estimator=KNeighborsClassifier()
    #加入网格搜索与交叉验证
    #参数准备
    param_dict={"n_neighbors":[1,3,5,7,9,11]}
    estimator=GridSearchCV(estimator,param_grid=param_dict,cv=10)
    estimator.fit(x_train,y_train)
    # 5.评估模型
    #方法一
    y_predict=estimator.predict(x_test)
    print("直接比对真实值和预测值:\n",y_test==y_predict)
    # 方法二
    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 None
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂的小强呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值