一、交叉验证(cross validation)
将拿到的训练数据,分为训练和验证集。以下图为例:将数据分成4份,其中一份作为验证集。然后经过4次(组)的测试,每次都更换不同的验证集。即得到4组模型的结果,取平均值作为最终结果。又称4折交叉验证。
二、超参数搜索-网格搜索
通常情况下,有很多参数是需要手动指定的(如k-近邻算法中的K值), 这种叫超参数。但是手动过程繁杂,所以需要对模型预设几种超参数组合。每组超参数都采用交叉验证来进行评估。最后选出最优参数组合建立模型。
k值 | k=3 | k=5 | k=7 |
---|---|---|---|
模型 | 模型1 | 模型2 | 模型3 |
三、模型选择与调优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 knn_iris_gscv():
# 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()
# 5) 网格搜索与交叉验证
garam_data={"n_neighbors":[1,3,5,7,9,11]}
estimator=GridSearchCV(estimator,garam_data,cv=10)
estimator.fit(x_train,y_train)
# 6) 模型评估
#方法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)
#最佳参数
print("最佳参数:",estimator.best_params_)
#最佳结果
print("最佳结果:",estimator.best_score_)
#最佳估计器
print("最佳估计器:",estimator.best_estimator_)
#交叉验证结果
print("交叉验证结果:",estimator.cv_results_)
knn_iris_gscv()