Skip to content

Models

Which model to try, what to tune first and what each one needs from preprocessing. This page has one table per task, a fast comparison loop, and the ensemble methods: bagging, random forests, boosting, voting and stacking. The examples use the bundled breast cancer and diabetes datasets, so they run in seconds. The blocks share one session:

import numpy as np
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one thread for OpenMP and BLAS: fast on small data
Xc, yc = load_breast_cancer(return_X_y=True, as_frame=True) # 569 rows, 30 features
Xr, yr = load_diabetes(return_X_y=True, as_frame=True) # 442 rows, 10 features
cv_c = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_r = KFold(n_splits=5, shuffle=True, random_state=42)

threadpool_limits(limits=1) caps the threads of the libraries that boosting and linear algebra use. On tables this small, threads cost more than they save. Scores do not change.

I want to… Use… Notes
a floor for any regressor DummyRegressor(strategy="mean") R² ≈ 0
a floor for any classifier DummyClassifier(strategy="most_frequent") accuracy = majority share
a linear regression LinearRegression() no tuning; no penalty
shrink correlated weights Ridge(alpha=1.0), RidgeCV(alphas=np.logspace(-3, 3, 13)) scale first
zero out useless weights Lasso(alpha=...), LassoCV(cv=5) scale first
mix L1 and L2 ElasticNet(alpha, l1_ratio=0.5), ElasticNetCV
a regression robust to outliers HuberRegressor(epsilon=1.35)
predict a median or other quantile QuantileRegressor(quantile=0.9, alpha=0) slow on big data; HGB loss="quantile"
counts or positive skewed targets PoissonRegressor(), TweedieRegressor(power=1.5), GammaRegressor() log link
a first, explainable classifier LogisticRegression(max_iter=1000) after scaling odds ratios
no penalty in logistic regression LogisticRegression(C=np.inf) penalty= is deprecated in 1.9
an L1 logistic regression LogisticRegression(l1_ratio=1, solver="liblinear") or "saga" sparse weights
a linear model on millions of rows SGDClassifier(loss="log_loss"), SGDRegressor() scale; partial_fit for streams
a linear SVM LinearSVC(C=1.0) no probabilities
a kernel SVM SVC(kernel="rbf", C=1, gamma="scale"), SVR small or medium data
similar rows vote KNeighborsClassifier(n_neighbors=5), KNeighborsRegressor scale first
a baseline for text counts MultinomialNB(), ComplementNB()
readable rules DecisionTreeClassifier(max_depth=4) sklearn.tree.export_text
a strong default with little tuning RandomForestClassifier(n_estimators=300, n_jobs=-1) oob_score=True
more randomness, faster forests ExtraTreesClassifier(), ExtraTreesRegressor() random split points
the best tabular accuracy HistGradientBoostingClassifier(), XGBoost, LightGBM see boosting
a small neural network MLPClassifier(hidden_layer_sizes=(64,), early_stopping=True) scale; PyTorch for more
bag any model BaggingClassifier(estimator, n_estimators=50, oob_score=True) variance down
boost stumps AdaBoostClassifier(n_estimators=100) the classic
average different models VotingClassifier(models, voting="soft") needs predict_proba
learn how to combine models StackingClassifier(models, final_estimator=LogisticRegression(), cv=5) out-of-fold
monotonic effects monotonic_cst=[1, 0, -1] on trees, forests and HGB business rules
one model per class pair OneVsOneClassifier(model), OneVsRestClassifier(model) multiclass from binary
several targets at once MultiOutputRegressor(model), RegressorChain(model)
list every estimator sklearn.utils.all_estimators(type_filter="classifier")
Class Key hyperparameters Scale? NaN Categories Notes
LinearRegression — for coefficients only no one-hot closed form; extrapolates linearly
Ridge, RidgeCV alpha yes no one-hot L2; never zero weights; fast
Lasso, LassoCV alpha yes no one-hot L1; selects features
ElasticNet, ElasticNetCV alpha, l1_ratio yes no one-hot correlated groups kept together
HuberRegressor epsilon, alpha yes no one-hot squared loss near 0, linear in the tails
QuantileRegressor quantile, alpha yes no one-hot linear quantiles; slow above ~10k rows
PoissonRegressor, GammaRegressor, TweedieRegressor alpha, power yes no one-hot GLMs for counts, costs, claims
SGDRegressor alpha, penalty, learning_rate yes no one-hot huge data; partial_fit
KNeighborsRegressor n_neighbors, weights yes no one-hot no training; never extrapolates
SVR C, epsilon, gamma yes no one-hot slow above ~20k rows
DecisionTreeRegressor max_depth, min_samples_leaf, ccp_alpha no yes ordinal or one-hot step function; unstable
RandomForestRegressor n_estimators, max_features, min_samples_leaf no yes ordinal or one-hot default max_features=1.0 is bagging; try 0.3–0.6
ExtraTreesRegressor as random forest no yes ordinal or one-hot no bootstrap by default
GradientBoostingRegressor learning_rate, n_estimators, max_depth, subsample no no ordinal or one-hot slow; small data only
HistGradientBoostingRegressor learning_rate, max_iter, max_leaf_nodes, l2_regularization no yes native (category dtype) fast; loss="poisson", "quantile"
xgboost.XGBRegressor n_estimators, learning_rate, max_depth, subsample no yes native see boosting
lightgbm.LGBMRegressor n_estimators, learning_rate, num_leaves, min_child_samples no yes native verbose=-1
MLPRegressor hidden_layer_sizes, alpha, learning_rate_init yes no one-hot needs many rows and tuning
Class Key hyperparameters Scale? NaN Categories Probabilities Notes
LogisticRegression C, l1_ratio, class_weight yes no one-hot yes, usually calibrated odds ratios; C smaller = stronger penalty
SGDClassifier loss, alpha, penalty yes no one-hot with loss="log_loss" big or streaming data
RidgeClassifier alpha yes no one-hot no fast multiclass linear baseline
LinearSVC C yes no one-hot no (decision_function) text, many features
SVC C, kernel, gamma yes no one-hot no; CalibratedClassifierCV probability= is deprecated in 1.9
KNeighborsClassifier n_neighbors, weights, metric yes no one-hot steps of 1/k slow predictions on big data
GaussianNB var_smoothing no no no poorly calibrated instant baseline
MultinomialNB, ComplementNB alpha no no counts poorly calibrated text counts
LinearDiscriminantAnalysis solver, shrinkage no no one-hot yes also a supervised projection
DecisionTreeClassifier max_depth, min_samples_leaf, ccp_alpha no yes ordinal or one-hot leaf shares readable; overfits alone
RandomForestClassifier n_estimators, max_features ("sqrt"), min_samples_leaf no yes ordinal or one-hot yes strong default
ExtraTreesClassifier as random forest no yes ordinal or one-hot yes faster, smoother
GradientBoostingClassifier learning_rate, n_estimators, max_depth no no ordinal or one-hot yes small data only
HistGradientBoostingClassifier learning_rate, max_iter, max_leaf_nodes, class_weight no yes native yes fast, strong default
xgboost.XGBClassifier n_estimators, learning_rate, max_depth, scale_pos_weight no yes native yes GPU support
lightgbm.LGBMClassifier n_estimators, learning_rate, num_leaves, class_weight no yes native yes very fast on big data
MLPClassifier hidden_layer_sizes, alpha, early_stopping yes no one-hot yes PyTorch for real deep learning

“NaN: yes” means the model accepts missing values in X (in scikit-learn 1.9: trees, random forests, extra trees, bagging and HGB; also XGBoost and LightGBM). Every other model needs an imputer in the pipeline. “Native” categories means a pandas category column, without encoding.

Every model gets the same folds. Scale-sensitive models carry their scaler in a pipeline:

from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
classifiers = {
"dummy": DummyClassifier(strategy="prior"),
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)),
"svc": make_pipeline(StandardScaler(), SVC()), # ranks with decision_function
"nb": GaussianNB(),
"tree": DecisionTreeClassifier(max_depth=4, random_state=42),
"forest": RandomForestClassifier(n_estimators=200, random_state=42),
"hgb": HistGradientBoostingClassifier(random_state=42),
}
for name, model in classifiers.items():
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc")
print(f"{name:<7} ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}")
Output
dummy ROC-AUC 0.500 ± 0.000
logreg ROC-AUC 0.995 ± 0.005
knn ROC-AUC 0.991 ± 0.008
svc ROC-AUC 0.995 ± 0.006
nb ROC-AUC 0.989 ± 0.006
tree ROC-AUC 0.915 ± 0.037
forest ROC-AUC 0.990 ± 0.008
hgb ROC-AUC 0.992 ± 0.006

This dataset is easy: every model except the dummy and the single tree scores above 0.98, and the gaps are smaller than one standard deviation. The single tree is the least stable model (the largest ± value).

from sklearn.dummy import DummyRegressor
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import HuberRegressor, LassoCV, RidgeCV
from sklearn.neighbors import KNeighborsRegressor
regressors = {
"dummy": DummyRegressor(),
"ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 13))),
"lasso": make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=42)),
"huber": make_pipeline(StandardScaler(), HuberRegressor(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=15)),
"forest": RandomForestRegressor(n_estimators=200, max_features=0.5,
min_samples_leaf=5, random_state=42),
"hgb": HistGradientBoostingRegressor(max_iter=100, learning_rate=0.05,
random_state=42),
}
for name, model in regressors.items():
r2 = cross_val_score(model, Xr, yr, cv=cv_r, scoring="r2")
print(f"{name:<6} R² {r2.mean():.3f} ± {r2.std():.3f}")
Output
dummy R² -0.019 ± 0.014
ridge R² 0.477 ± 0.083
lasso R² 0.474 ± 0.086
huber R² 0.476 ± 0.079
knn R² 0.433 ± 0.041
forest R² 0.455 ± 0.081
hgb R² 0.433 ± 0.082

On 442 rows of mostly linear signal, Ridge beats the forest and boosting. Tree ensembles usually pull ahead on larger tables with interactions and non-linear effects. Always run the linear baseline.

Situation First choice Then try
any new tabular problem dummy baseline + HistGradientBoosting* linear model for comparison
coefficients must be explained LogisticRegression, Ridge, a GLM add splines or interactions
a few hundred rows regularized linear model, small forest SVM with tuned C and gamma
millions of rows LightGBM, HistGradientBoosting*, SGD* XGBoost on GPU
thousands of sparse features (text) LogisticRegression, LinearSVC, ComplementNB SGDClassifier
many missing values HGB, XGBoost, LightGBM, trees and forests imputer + indicator for the others
high-cardinality categories HGB, LightGBM, XGBoost with native categories TargetEncoder for linear models
counts or skewed positive targets PoissonRegressor, HGB loss="poisson" log target
an interval, not a point HGB or LightGBM with loss="quantile" QuantileRegressor
images, audio, long text neural networks (PyTorch) pretrained models
Hyperparameter More flexible (variance up) Simpler (bias up)
C (logistic, SVM) larger smaller
alpha (Ridge, Lasso, GLMs, MLP) smaller larger
n_neighbors smaller larger
max_depth, max_leaf_nodes, num_leaves larger smaller
min_samples_leaf, min_child_samples smaller larger
gamma (RBF SVM) larger smaller
learning_rate × rounds (boosting) larger smaller
Method Base models Built Combined by Reduces scikit-learn
bagging one model on bootstrap samples in parallel mean or vote variance BaggingClassifier, BaggingRegressor
random forest deep trees, bootstrap + random features per split in parallel mean of probabilities variance RandomForest*
extra trees deep trees, random split thresholds in parallel mean variance ExtraTrees*
AdaBoost stumps on reweighted rows in sequence weighted vote bias AdaBoost*
gradient boosting small trees on the gradient of the loss in sequence sum of trees × learning rate bias GradientBoosting*, HistGradientBoosting*
voting different models in parallel mean of labels or probabilities variance (if diverse) VotingClassifier, VotingRegressor
stacking different models in parallel + a meta-model learned weights on out-of-fold predictions both (if diverse) StackingClassifier, StackingRegressor

Averaging MM models with error variance σ2\sigma^2 and error correlation ρ\rho leaves a variance of

Var⁡(eˉ)=ρ σ2+1−ρM σ2\operatorname{Var}(\bar{e}) = \rho\,\sigma^2 + \frac{1 - \rho}{M}\,\sigma^2

More models shrink only the second term. Only more diverse models (lower ρ\rho) shrink the first.

Parameter Bagging / forest Effect
n_estimators 100–500 more is never worse, only slower
max_features forest: "sqrt" (classifier), 1.0 (regressor) lower = more diverse trees
max_samples None = n rows smaller = faster, more diverse
min_samples_leaf 1 larger = smoother, smaller files
oob_score=True — a free validation score from the out-of-bag rows (~36.8%)
warm_start=True — add trees to a fitted forest
n_jobs=-1 — trees in parallel
from sklearn.ensemble import (
AdaBoostClassifier,
BaggingClassifier,
ExtraTreesClassifier,
StackingClassifier,
VotingClassifier,
)
forest = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=42)
print(f"forest OOB accuracy {forest.fit(Xc, yc).oob_score_:.3f}") # no CV needed
ensembles = {
"bagged tree": BaggingClassifier(DecisionTreeClassifier(), n_estimators=100,
random_state=42),
"extra trees": ExtraTreesClassifier(n_estimators=200, random_state=42),
"adaboost": AdaBoostClassifier(n_estimators=100, random_state=42),
}
for name, model in ensembles.items():
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc").mean()
print(f"{name:<11} ROC-AUC {auc:.3f}")
Output
forest OOB accuracy 0.960
bagged tree ROC-AUC 0.988
extra trees ROC-AUC 0.994
adaboost ROC-AUC 0.993
Hard voting Soft voting Stacking
combines labels probabilities out-of-fold predictions
weights fixed (weights=) fixed (weights=) learned by final_estimator
predict_proba no yes yes
extra fits none none cv per base model, plus one refit each
key options voting="hard" voting="soft", weights cv, stack_method, passthrough=True (add raw features)
members = [
("logreg", classifiers["logreg"]),
("knn", classifiers["knn"]),
("forest", RandomForestClassifier(n_estimators=200, random_state=42)),
]
soft = VotingClassifier(members, voting="soft")
stack = StackingClassifier(members, final_estimator=LogisticRegression(), cv=cv_c)
for name, model in [("soft voting", soft), ("stacking", stack)]:
auc = cross_val_score(model, Xc, yc, cv=cv_c, scoring="roc_auc")
print(f"{name:<11} ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}")
print("meta weights:", stack.fit(Xc, yc).final_estimator_.coef_.round(2))
Output
soft voting ROC-AUC 0.996 ± 0.005
stacking ROC-AUC 0.996 ± 0.005
meta weights: [[3.94 2.6 2.45]]

An ensemble earns its cost only when the gain beats the fold-to-fold noise and the members disagree. Two models whose predictions correlate at 0.95 or more add little.

Trap Symptom Fix
no scaling before KNN, SVM, penalized linear models, MLP the largest-unit column dominates; weak scores StandardScaler in the pipeline
LogisticRegression(penalty="l1") FutureWarning in scikit-learn 1.9 l1_ratio=1 with solver="liblinear" or "saga"; C=np.inf for no penalty
SVC(probability=True) deprecated in 1.9, slow, can contradict predict decision_function, or CalibratedClassifierCV(SVC(), ensemble=False)
ConvergenceWarning from a linear model or MLP unscaled data or too few iterations scale; raise max_iter
RandomForestRegressor() defaults max_features=1.0: bagging, correlated trees max_features 0.3–0.6
an unlimited DecisionTree* training score 1.0, weak validation score max_depth, min_samples_leaf or ccp_alpha
trees, forests, KNN outside the training range flat predictions at the edge linear terms, a log or ratio target
GaussianNB probabilities almost always 0 or 1 use it for ranking, or calibrate
GradientBoosting* on large data very slow HistGradientBoosting*
hard voting no predict_proba, so no ROC-AUC or threshold voting="soft"
stacking on in-sample predictions the meta-model trusts the most overfit member StackingClassifier with cv (the default does it)
criterion="friedman_mse" deprecated in scikit-learn 1.9 leave the default
comparing models on different folds differences come from the split, not the model one splitter object for every model
a small CV gain noise read as signal compare the paired fold scores; keep the simpler model