模型选择与调优

交叉验证#

将训练数据分为n份,经过n组测试,取平均值得到最终结果,称作n折交叉验证。

使得被评估的模型更加准确可信。

如四折交叉验证: 四折交叉验证

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

模型中,需要手动指定的参数(如KNN中的k值)称作超参数。

可通过已指定好的参数网格,遍历搜索选取最佳参数。

模型选择与调优API#

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

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

API使用#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier, export_graphviz
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_)

return None