Skip to content

sklearn/manual-param-sweep

Pack Severity Fix Versions
scikit-learn warning none, edit by hand All versions

A loop that builds and fits a model once per hyperparameter value and scores each fit by hand reimplements validation_curve and GridSearchCV. For the penalty of a linear model, the CV estimators choose the value in one fit.

scores = []
for k in range(1, 30):
knn = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
scores.append(knn.score(X_val, y_val))
train, test = validation_curve(KNeighborsClassifier(), X, y, param_name="n_neighbors", param_range=range(1, 30), cv=5, n_jobs=-1)

The rule reports the estimator call in a loop or comprehension when one of its keyword arguments is the loop name, and the loop body fits a model and predicts or scores with it.

  • Penalty sweep: Ridge, RidgeClassifier, Lasso, ElasticNet, LassoLars or LogisticRegression with alpha=, C= or l1_ratio= taken from the loop.
  • Coefficient path: Lasso or ElasticNet with alpha= from the loop, where the loop reads coef_ and scores nothing.
  • Other hyperparameters: any classifier or regressor with a swept keyword such as n_neighbors, max_depth or learning_rate.
  • Factory sweeps: a function such as make(a, b) called with the loop name over a grid of numbers, range(...), np.linspace(...) or a name such as alphas or depths, whose model is fitted and scored or passed to cross_val_score. A loop over model names or strings is left alone.
  • Candidate configurations: Est(**cfg) or model.set_params(**cfg) for each configuration of a loop, fitted and scored or passed to a CV helper.
  • Quantile loops: XGBRegressor(quantile_alpha=q) once per quantile, and, as info, GradientBoostingRegressor(loss="quantile", alpha=q), HistGradientBoostingRegressor(loss="quantile", quantile=q) or LGBMRegressor(objective="quantile", alpha=q). A loop of the linear QuantileRegressor is left alone, because no estimator fits several linear quantiles in one fit.

It leaves alone a loop over n_estimators, which refit-per-n-estimators covers, over a seed, a cluster count or quantile, a loop that already calls a CV helper or a search, which manual-cv-loop covers, and a loop that reports to Optuna.

xpd has no automatic fix, so replace the loop by hand.

  • Penalties: RidgeCV(alphas=...), RidgeClassifierCV(alphas=...), LassoCV, ElasticNetCV(l1_ratio=[...]), LassoLarsCV or LogisticRegressionCV(Cs=...).
  • Coefficients at every alpha: lasso_path(X, y, alphas=...) or enet_path(X, y, l1_ratio=..., alphas=...). scikit-learn 1.9.1 has no ridge path function.
  • Scores per value: validation_curve(est, X, y, param_name=..., param_range=..., cv=..., n_jobs=-1).
  • The best value refitted: GridSearchCV or HalvingGridSearchCV. Pass a fixed validation set as cv=PredefinedSplit(test_fold).
  • A factory: make the swept value a parameter of an estimator or a Pipeline step, so GridSearchCV can set it.
  • Candidate configurations: GridSearchCV(est, param_grid=[{key: [value] for key, value in cfg.items()} for cfg in candidates]) evaluates the same list, and RandomizedSearchCV or OptunaSearchCV fit random draws.
  • Quantiles: XGBRegressor(objective="reg:quantileerror", quantile_alpha=[0.1, 0.5, 0.9]) fits every quantile in one model, and predict returns one column per quantile. On xgboost 3.4.1 it matched one model per quantile within 0.002. For other boosted models, quantile-forest RandomForestQuantileRegressor().fit(X, y).predict(X, quantiles=[...]) also predicts any quantiles from one fit, with a different learner.
This refits $EST once per value of $K=$P. Choose the penalty in one estimator with its CV form, RidgeCV(alphas=...), RidgeClassifierCV(alphas=...), LassoCV(alphas=...), ElasticNetCV(l1_ratio=[...]), LassoLarsCV or LogisticRegressionCV(Cs=...), and use lasso_path or enet_path when you need the coefficients at every alpha.

See all rules in the scikit-learn pack.