天天看点

Scikit-learn_模型评估和参数调优_参数调优一.描述二.实例

一.描述

  • 网格搜索法
    • 是遍历多个参数多个取值的全部组合,使用每一组参数组合做训练和评估测试,记录评估结果,最终找出最优评估结果,该结果对应的参数就是最优参数。
    • 训练的时间与数据集大小、训练次数、参数数量以及每个参数的取值数量正相关。当数据集较大时,网格搜索法耗时非常长。因此使用网格搜索法参数调优(调参)时,应尽可能减少参与调参的参数个数,限制每一个参数的取值数量
  • 随机搜索法
    • 随机搜索法类似于网格搜索法,只是不需要给出每个参数的取值,而是给出每个参数的取值范围。该方法会在每个参数的取值范围内随机取值,得到参数组合并对其进行训练和评估。
    • 随机搜索发适用于参数取值不确定,需要再较大的范围内寻找最优参数的场合

二.实例

import numpy as np
x, y = np.mgrid[-2:2:50j, -2:2:50j]
z = x * np.exp(-x ** 2 -y ** 2)
_x = np.random.random(1000) * 4 - 2
_y = np.random.random(1000) * 4 - 2
_z = _x * np.exp(-_x ** 2 - _y ** 2) + (np.random.random(1000) - 0.5) * 0.1
# 训练样本集
X_train = np.stack((_x, _y), axis=1)
# 训练标签集
y_train = _z
# 测试样本集
X_test = np.stack((x.ravel(), y.ravel()), axis=1)
# 测试标签集
y_test = z.ravel()
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
args = {
    # 指定参数的7种取值
    'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
    'gamma': [0.001, 0.01, 0.1, 1, 10, 100, 1000]
}
# 实例化网格搜索器
gs = GridSearchCV(SVR(), args, cv=5)
gs.fit(X_train, y_train)
# 评估网格搜索器
gs.score(X_test, y_test)
# 当前最优参数
gs.best_params_
%matplotlib
# 对测试集做回归分析
z_gs = gs.predict(X_test)
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='3d')
ax.scatter3D(_x, _y, _z, c='r')
ax.plot_surface(x, y, z_gs.reshape(x.shape), cmap=plt.cm.hsv, alpha=0.5)
plt.show()