<jupyter_start><jupyter_text>内容概要- 如何使用K折交叉验证来搜索最优调节参数- 如何让搜索参数的流程更加高效- 如何一次性的搜索多个调节参数- 在进行真正的预测之前，如何对调节参数进行处理- 如何削减该过程的计算代价  1. K折交叉验证回顾**交叉验证的过程**- 选择K的值（一般是10），将数据集分成K等份- 使用其中的K-1份数据作为训练数据，另外一份数据作为测试数据，进行模型的训练- 使用一种度量测度来衡量模型的预测性能**交叉验证的优点**- 交叉验证通过降低模型在一次数据分割中性能表现上的方差来保证模型性能的稳定性- 交叉验证可以用于选择调节参数、比较模型性能差别、选择特征**交叉验证的缺点**- 交叉验证带来一定的计算代价，尤其是当数据集很大的时候，导致计算过程会变得很慢  2. 使用GridSearchCV进行高效调参GridSearchCV根据你给定的模型自动进行交叉验证，通过调节每一个参数来跟踪评分结果，实际上，该过程代替了进行参数搜索时的for循环过程。<jupyter_code>from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.grid_search import GridSearchCV
# read in the iris data
iris = load_iris()

# create X (features) and y (response)
X = iris.data
y = iris.target
# define the parameter values that should be searched
k_range = range(1, 31)
print k_range
# create a parameter grid: map the parameter names to the values that should be searched
# 下面是构建parameter grid，其结构是key为参数名称，value是待搜索的数值列表的一个字典结构
param_grid = dict(n_neighbors=k_range)
print param_grid
knn = KNeighborsClassifier(n_neighbors=5)
# instantiate the grid
# 这里GridSearchCV的参数形式和cross_val_score的形式差不多，其中param_grid是parameter grid所对应的参数
# GridSearchCV中的n_jobs设置为-1时，可以实现并行计算（如果你的电脑支持的情况下）
grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy')<jupyter_output><empty_output><jupyter_text>我们可以知道，这里的grid search针对每个参数进行了10次交叉验证，并且一共对30个参数进行相同过程的交叉验证<jupyter_code>grid.fit(X, y)
# view the complete results (list of named tuples)
grid.grid_scores_
# examine the first tuple
print grid.grid_scores_[0].parameters
print grid.grid_scores_[0].cv_validation_scores
print grid.grid_scores_[0].mean_validation_score
# create a list of the mean scores only
grid_mean_scores = [result.mean_validation_score for result in grid.grid_scores_]
print grid_mean_scores
# plot the results
plt.plot(k_range, grid_mean_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Validated Accuracy')
# examine the best model
print grid.best_score_
print grid.best_params_
print grid.best_estimator_<jupyter_output>0.98
{'n_neighbors': 13}
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_neighbors=13, p=2, weights='uniform')<jupyter_text>3. 同时对多个参数进行搜索这里我们使用knn的两个参数，分别是n_neighbors和weights，其中weights参数默认是uniform，该参数将所有数据看成等同的，而另一值是distance，它将近邻的数据赋予更高的权重，而较远的数据赋予较低权重。<jupyter_code># define the parameter values that should be searched
k_range = range(1, 31)
weight_options = ['uniform', 'distance']
# create a parameter grid: map the parameter names to the values that should be searched
param_grid = dict(n_neighbors=k_range, weights=weight_options)
print param_grid
# instantiate and fit the grid
grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy')
grid.fit(X, y)
# view the complete results
grid.grid_scores_
# examine the best model
print grid.best_score_
print grid.best_params_<jupyter_output>0.98
{'n_neighbors': 13, 'weights': 'uniform'}<jupyter_text>4. 使用最佳参数做出预测<jupyter_code># train your model using all data and the best known parameters
knn = KNeighborsClassifier(n_neighbors=13, weights='uniform')
knn.fit(X, y)

# make a prediction on out-of-sample data
knn.predict([3, 5, 4, 2])<jupyter_output><empty_output><jupyter_text>**这里使用之前得到的最佳参数对模型进行重新训练，在训练时，就可以将所有的数据都作为训练数据全部投入到模型中去，这样就不会浪费个别数据了。**<jupyter_code># shortcut: GridSearchCV automatically refits the best model using all of the data
grid.predict([3, 5, 4, 2])<jupyter_output><empty_output><jupyter_text>5. 使用RandomizeSearchCV来降低计算代价- RandomizeSearchCV用于解决多个参数的搜索过程中计算代价过高的问题- RandomizeSearchCV搜索参数中的一个子集，这样你可以控制计算代价![](Image/grid_vs_random.jpeg)<jupyter_code>from sklearn.grid_search import RandomizedSearchCV
# specify "parameter distributions" rather than a "parameter grid"
param_dist = dict(n_neighbors=k_range, weights=weight_options)
# n_iter controls the number of searches
rand = RandomizedSearchCV(knn, param_dist, cv=10, scoring='accuracy', n_iter=10, random_state=5)
rand.fit(X, y)
rand.grid_scores_
# examine the best model
print rand.best_score_
print rand.best_params_
# run RandomizedSearchCV 20 times (with n_iter=10) and record the best score
best_scores = []
for _ in range(20):
    rand = RandomizedSearchCV(knn, param_dist, cv=10, scoring='accuracy', n_iter=10)
    rand.fit(X, y)
    best_scores.append(round(rand.best_score_, 3))
print best_scores<jupyter_output>[0.98, 0.98, 0.973, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.973, 0.98, 0.98, 0.98, 0.973, 0.98, 0.98, 0.973, 0.973]
{'fraction_non_alphanumeric': 0.09705295812098383, 'fraction_numerical': 0.029470418790161754, 'mean_word_length': 7.81640625, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '552702', 'license': 'MIT', 'n_tokens_mistral': 2157, 'n_tokens_neox': 2215, 'n_words': 359, 'path': 'Scikit-learn/.ipynb_checkpoints/(5)grid_search-checkpoint.ipynb', 'repo_name': 'Mr-Dou/pyDataScienceToolkits', 'size': '4513'}