
216
|
第
12
章
模型选择
12.2
使用随机搜索选择最佳模型
问题描述
使用一种比穷举搜索更节省计算资源的方法来选择最佳模型。
解决方案
使用
scikit-learn
的
RandomizedSearchCV
:
#
加载库
from scipy.stats import uniform
from sklearn import linear_model, datasets
from sklearn.model_selection import RandomizedSearchCV
#
加载数据
iris = datasets.load_iris()
features = iris.data
target = iris.target
#
创建逻辑回归对象
logistic = linear_model.LogisticRegression()
#
创建正则化惩罚的候选超参数区间
penalty = [
'
l1
'
,
'
l2
'
]
#
创建正则化候选超参数的分布
C = uniform(loc=0, scale=4)
#
创建超参数字典
hyperparameters = dict(C=C, penalty=penalty)
#
创建随机搜索对象
randomizedsearch = RandomizedSearchCV(
logistic, hyperparameters, random_state=1, n_iter=100, cv=5, ...