zoukankan      html  css  js  c++  java
  • hyperopt自动调参

    hyperopt自动调参

    在传统机器学习和深度学习领域经常需要调参,调参有些是通过通过对数据和算法的理解进行的,这当然是上上策,但还有相当一部分属于"黑盒"

    hyperopt可以帮助我们做很多索然无味的调参工作

    示例

    直接看代码以及注释比较直接,下面通过一个随机森林可以感受一下:

    # coding=utf-8
    
    from sklearn import datasets
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.cross_validation import cross_val_score
    from sklearn.preprocessing import scale, normalize
    from hyperopt import hp, STATUS_OK, Trials, fmin, tpe
    
    
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    
    
    def hyperopt_train_test(params):
        X_ = X[:]
        # 这里可以自定义一些操作
        if params['normalize']:
            X_ = normalize(X_)
        if params['scale']:
            X_ = scale(X_)
    
        del params['normalize']
        del params['scale']
    
        clf = RandomForestClassifier(**params)
        # 交叉验证
        return cross_val_score(clf, X, y, cv=10).mean()
    
    
    space_rf = {
        'max_depth': hp.choice('max_depth', range(1, 20)),
        'max_features': hp.choice('max_features', range(1, 5)),
        'n_estimators': hp.choice('n_estimators', range(1, 20)),
        'criterion': hp.choice('criterion', ["gini", "entropy"]),
        'scale': hp.choice('scale', [True, False]),
        'normalize': hp.choice('normalize', [True, False])
    }
    
    
    # 待优化目标函数
    def f(params):
        acc = hyperopt_train_test(params)
        return {'loss': -acc, 'status': STATUS_OK}
    
    
    trials = Trials()
    best = fmin(f,  # 待最小化函数
                space=space_rf,  # 参数所搜索空间
                algo=tpe.suggest,  # 算法选择,这里选择了TPE,也可以用rand.suggest等
                max_evals=50,  #  迭代次数
                trials=trials,  # 可以用trials数组记录中间结果
                )
    
    # best是loss最小的参数组合
    # 对于离散值,如criterion,会返回选择的元素索引
    print(best)
    loss = []
    for trial in trials.results:
        loss.append(trial['loss'])
    print(min(loss))
    

    运行输出

    {'normalize': 1, 'scale': 0, 'n_estimators': 14, 'criterion': 1, 'max_features': 1, 'max_depth': 11}
    -0.973333333333
    

    小结

    hyperopt还有很多高阶用法,如借助mongo并行化,但基本的使用架构上面的demo应该已经很好的体现了

    超参调优是一个很大的问题,很多启发式算法会被采用,如数学建模中的一些优化算法

  • 相关阅读:
    sentinel-initFunc&控制台
    Sentinel-FlowSlot
    Sentinel-AuthoritySlot&SystemSlot&LogSlot
    Sentinel-DegradeSlot
    Sentinel-ClusterBuilderSlot
    Sentinel-NodeSelectorSlot
    Sentinel整体架构
    Recyclers对象池设计
    加密算法的使用场景
    FastDFS分布式
  • 原文地址:https://www.cnblogs.com/fanghao/p/9832403.html
Copyright © 2011-2022 走看看