今日必看|调整超参数:决定模型是“金子”仍是“垃圾”!( 二 )


参数设置和模型评估可以使用sklearn中的GridSearchCV进行调用 。
网格搜索的上风:
可以选用任何你以为可能是最佳参数范围的超参数集合进行模型练习 。搜索的劣势:
网格搜索较为耗时 , 由于要运行给定的每一个超参数集 。 所以 , 假如参数集较大 , 则网格搜索的运行本钱较高 。 实际上 , 网格搜索的参数范围是需要被限制的 , 即不能无限大 。以LGBMRegressor模型为例 , 分别设置了“max_depth” , “subsample” , “colsample_bytree” , “min_child_weight”超参数 , 它的评分器是“r2” , 可能的组合个数是3*2*2*3=36 , 即需要练习36次LGBMRegressor模型 , 如下是代码示例:
# 导入lightgbm库
from lightgbm import LGBMRegressor
# 导入网格搜索
from sklearn.model_selection import train_test_split, GridSearchCV
import pandas as pd
import numpy as np
# 导入数据并拆分练习集
df = pd.read_csv("test.csv",index_col=0)
y = df["Target"]
X = df.drop(["Targe"],axis=1)
X_train0, X_test, y_train0, y_test = train_test_split(X,y,test_size=0.2, random_state= 2)
# 定义验证集比例
r = 0.1
trainLen = round(len(X_train0)*(1-r))
# 拆分练习集和验证集
X_train = X_train0.iloc[:trainLen,:]
y_train = y_train0[:trainLen]
X_val = X_train0.iloc[trainLen:,:]
y_val = y_train0[trainLen:]
# 定义网格搜索参数
gridParams = {
"max_depth": [3, 5, 7],
"subsample": [0.8, 1.0],
"colsample_bytree": [0.8, 1.0],
"min_child_weight": [0.1, 1.0, 2.0],
}
# 定义lightgbm网格搜索
reg = LGBMRegressor(learning_rate=0.1, n_estimators=1000, random_state=1000)
reg_gridsearch = GridSearchCV(reg, gridParams, cv=5, scoring="r2", n_jobs=-1)
# 练习模型
reg_gridsearch.fit(X_train, y_train, early_stopping_rounds=100, eval_set=(X_val,y_val))
# 返回最佳参数
reg_gridsearch.best_params_
代码参考:https://gist.githubusercontent.com/daydreamersjp/0e588d805be6d6b755c68fa1e8095fc4/raw/e0eb0af142db38fb3ceb48b1f37e2a22671afd0a/gistfile2019120801.py
2.3 随机搜索
随机搜索是基于网格搜索的延伸 , 它与网格搜索一样 , 需要预先指定超参数的候选集 。 随机搜索会随机的从参数候选集中选取参数 , 练习模型 。 随机搜索从由所有可能的超参数组合中随机抽取“组合”以练习模型 , 使用者可以通过设置最大迭代次数 , 来调节模型的运行次数 。 相对网格搜索而言 , 随机搜索的计算成本更低 , 结果精度相对较低 , 它返回一个比较general的模型可能实现的水平 。 随机搜索与网格搜索的返回值相同 , 均是各自策略下模型的最佳超参数 。
随机搜索还可以设置参数的密度函数 , 例如:均匀分布或者正态分布 。
可以在如下库中实现上述操纵 , 如:sklearn中的RandomizedSearchCV 。
随机搜索的上风:
你可以通过控制参数搜索的次数 , 控制随机搜索的运行本钱 。随机搜索的劣势:
它是一种“权衡”策略 , 运行本钱和搜索精度的“权衡” 。 随机搜索返回的最佳参数可能不是模型实际的最佳参数 。因为设置最大搜索次数 , 因此 , 一些参数可能被遍历的次数有限 。随机搜索不提供随机抽取超参数的方法 。以LGBMRegressor模型为例 , 分别设置了“max_depth” , “subsample” , “colsample_bytree” , “min_child_weight” , 它的评分器为“r2” , 最大迭代次数为20 , 代码示例如下:
# 导入LGBMRegressor
from lightgbm import LGBMRegressor
# 导入网格搜索
from sklearn.model_selection import train_test_split, RandomizedSearchCV
【今日必看|调整超参数:决定模型是“金子”仍是“垃圾”!】# 可用于声明参数分布
import scipy.stats as stats
import pandas as pd
import numpy as np
# 导入数据集 , 将数据集拆分为练习/测试集
df = pd.read_csv("test.csv",index_col=0)
y = df["Target"]
X = df.drop(["Target"],axis=1)
X_train0, X_test, y_train0, y_test = train_test_split(X,y,test_size=0.2, random_state= 2)
# 练习集的比例
r = 0.1
trainLen = round(len(X_train0)*(1-r))
# 拆分练习集和验证集
X_train = X_train0.iloc[:trainLen,:]
y_train = y_train0[:trainLen]
X_val = X_train0.iloc[trainLen:,:]
y_val = y_train0[trainLen:]
# 定义网格搜索空间
randParams = {
"max_depth": stats.randint(1,10), # 介于1到10的整数
"subsample": stats.uniform(0.6,1.0-0.6), # 介于0.6到1的值
"colsample_bytree": stats.uniform(0.6,1.0-0.6), # 介于0.6到1的值


推荐阅读