前言
在KNN算法中,k值的选择对我们最终的预测结果有着很大的影响
那么有没有好的方法能够帮助我们选择好的k值呢?
模型选择与调优
目标
-
说明交叉验证过程
-
说明参数搜索过程
-
应用GirdSearchCV实现算法参数的调优
应用
Facebook 签到位置预测调优
什么是交叉验证(cross validation)
定义
将拿到的训练数据,分为训练和验证集,以下图为例:将数据分成4份,其中一份作为验证集,然后经过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:准确率
-
结果分析:
-
bestscore:在交叉验证中验证的最好结果_
-
bestestimator:最好的参数模型
-
cvresults:每次交叉验证后的验证集准确率结果和训练集准确率结果
鸢尾花案例增加K值调优
使用GridSearchCV构建估计器
def knn_iris_gscv():
"""
用KNN算法对鸢尾花进行分类,添加网格搜索和交叉验证
:return:
"""
# 1)获取数据
iris = load_iris()
# 2)划分数据集
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=22)
# 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)模型评估
# 方法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_)