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)What the rule reports
Section titled “What the rule reports”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,LassoLarsorLogisticRegressionwithalpha=,C=orl1_ratio=taken from the loop. - Coefficient path:
LassoorElasticNetwithalpha=from the loop, where the loop readscoef_and scores nothing. - Other hyperparameters: any classifier or regressor with a swept keyword such as
n_neighbors,max_depthorlearning_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 asalphasordepths, whose model is fitted and scored or passed tocross_val_score. A loop over model names or strings is left alone. - Candidate configurations:
Est(**cfg)ormodel.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)orLGBMRegressor(objective="quantile", alpha=q). A loop of the linearQuantileRegressoris 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.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so replace the loop by hand.
- Penalties:
RidgeCV(alphas=...),RidgeClassifierCV(alphas=...),LassoCV,ElasticNetCV(l1_ratio=[...]),LassoLarsCVorLogisticRegressionCV(Cs=...). - Coefficients at every alpha:
lasso_path(X, y, alphas=...)orenet_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:
GridSearchCVorHalvingGridSearchCV. Pass a fixed validation set ascv=PredefinedSplit(test_fold). - A factory: make the swept value a parameter of an estimator or a Pipeline step, so
GridSearchCVcan set it. - Candidate configurations:
GridSearchCV(est, param_grid=[{key: [value] for key, value in cfg.items()} for cfg in candidates])evaluates the same list, andRandomizedSearchCVorOptunaSearchCVfit random draws. - Quantiles:
XGBRegressor(objective="reg:quantileerror", quantile_alpha=[0.1, 0.5, 0.9])fits every quantile in one model, andpredictreturns one column per quantile. On xgboost 3.4.1 it matched one model per quantile within 0.002. For other boosted models, quantile-forestRandomForestQuantileRegressor().fit(X, y).predict(X, quantiles=[...])also predicts any quantiles from one fit, with a different learner.
Diagnostic message
Section titled “Diagnostic message”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.