【问题标题】:Can you iterate over hyperparameters in scikit?你能在 scikit 中迭代超参数吗?
【发布时间】:2022-11-19 11:26:49
【问题描述】:

有没有办法迭代随机森林模型,以便我创建一个具有不同超参数的新模型?

IE。

model = RandomForestClassifier(n_estimators= N, max_depth= D) 

我希望能够为范围为 1 - 25 和 D 1 - 5 的每个 N 值构建一个模型。

这可能吗?

谢谢

【问题讨论】:

    标签: pandas scikit-learn


    【解决方案1】:

    迭代超参数和训练/测试模型的方法不止一种。一个简单的方法是:

    from sklearn import ensemble
    from sklearn import model_selection
    
    # generating parameter grid
    params = {
        "n_estimators": list(range(1,26)),
        "max_depth": list(range(1,6)),
    }
    grid = model_selection.ParameterGrid(params)
    
    # iterate over grid and fit/score model with the varying hyperparameters
    for param in grid:
        rf_clf = ensemble.RandomForestClassifier(**param)  # unpacking param which is a dictionary
        rf_clf.fit(x_train, y_train)
        print(rf_clf.score(x_val, y_val), param)
    
    

    包括交叉验证的另一种方法是:

    from sklearn import ensemble
    from sklearn import metrics
    from sklearn import model_selection
    
    
    rf_clf = ensemble.RandomForestRegressor()
    params = {
        "n_estimators": list(range(1,26)),
        "max_depth": list(range(1,6)),
    }
    cv = model_selection.GridSearchCV(
        estimator=rf_clf,
        param_grid=params,
        scoring=metrics.accuracy_score # scorer of choice (optional)
    )
    cv.fit(x_train, y_train)  # performs cross-validation and saves per-model info
    
    # access GridSearchCV object how you like. For example:
    print(cv.best_score_, cv.best_params_)
    print(cv.cv_results_)
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2017-12-03
      • 2019-03-28
      相关资源
      最近更新 更多