【模型选择与评估02】调整估计器的超参数

1.参考文献
sklearn文档

背景:

超参数,即不直接在估计器内学习的参数。在 scikit-learn 包中,它们作为估计器类中构造函数的参数进行传递。搜索超参数空间以便获得最好分数的方法是可能的而且是值得提倡的。通过这种方式,构造估计器时被提供的任何参数或许都能被优化。
具体来说,要获取到给定估计器的所有参数的名称和当前值,使用:

estimator.get_params()

搜索包括:
估计器(回归器或分类器,例如 sklearn.svm.SVC())
参数空间
搜寻或采样候选的方法
交叉验证方案
计分函数

1.网格搜索法

网格搜索核心基于:
sklearn.model_selection.GridSearchCV 

使用示例:
from __future__ import print_function
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC

print(__doc__)

# Loading the Digits dataset
digits = datasets.load_digits()

# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
X = digits.images.reshape((n_samples, -1))
y = digits.target

# Split the dataset in two equal parts
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=0)

下面的tuned_parameters设定了进行网格搜索的各参数的取值情况,便于使用
# Set the parameters by cross-validation
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
                     'C': [1, 10, 100, 1000]},
                    {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]

这是两种评价指标,精确度和召回率,可以分别针对这两个指标进行网格搜索
scores = ['precision', 'recall']

for score in scores:
    print("# Tuning hyper-parameters for %s" % score)
    print()
 
**********这里是网格搜索的核心位置,所需参数包括:评估器、网格参数、交叉验证折数、评价指标!!!**************
    clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
                       scoring='%s_macro' % score)
    clf.fit(X_train, y_train)
******************************************************************************************************

    print("Best parameters set found on development set:")
    print()
    print(clf.best_params_)
    print()
    print("Grid scores on development set:")
    print()
    means = clf.cv_results_['mean_test_score']
    stds = clf.cv_results_['std_test_score']
    for mean, std, params in zip(means, stds, clf.cv_results_['params']):
        print("%0.3f (+/-%0.03f) for %r"
              % (mean, std * 2, params))
    print()

    print("Detailed classification report:")
    print()
    print("The model is trained on the full development set.")
    print("The scores are computed on the full evaluation set.")
    print()
    y_true, y_pred = y_test, clf.predict(X_test)
    print(classification_report(y_true, y_pred))
    print()

2.随机搜索

随机搜索核心基于:
sklearn.model_selection.RandomizedSearchCV

其中每个设置都是从可能的参数值的分布中进行取样。 这对于穷举搜索有两个主要优势:
(1)可以选择独立于参数个数和可能值的预算
(2)添加不影响性能的参数不会降低效率

指定如何取样的参数是使用字典完成的, 非常类似于为 GridSearchCV 指定参数。
此外, 通过 n_iter 参数指定计算预算, 即取样候选项数或取样迭代次数。 
对于每个参数, 可以指定在可能值上的分布或离散选择的列表 (均匀取样):
{'C': scipy.stats.expon(scale=100), 'gamma': scipy.stats.expon(scale=.1),
  'kernel': ['rbf'], 'class_weight':['balanced', None]}
本示例使用 scipy.stats 模块, 它包含许多用于采样参数的有用分布, 如 expon,gamma,uniform 或者 randint。
原则上,任何函数都可以通过提供一个rvs(随机变量样本)方法来采样一个值。
对 rvs 函数的调用应在连续调用中提供来自可能参数值的独立随机样本。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值