Gradient boosting builds a classifier from a sequence of small decision trees, with each new tree correcting the errors left by the trees before it. In scikit-learn, HistGradientBoostingClassifier trains that model directly on tabular rows with missing feature values and can stop adding trees on its own, leaving a fitted classifier that predicts held-out rows with their NaN cells still in place.

Estimators such as LogisticRegression reject NaN cells, which leaves imputation or dropped rows as the usual workarounds. The histogram-based estimator instead learns at each split which side receives rows with a missing value, so those rows stay in training and prediction without a preprocessing step. That difference grows when gaps are spread across columns, because dropping every row with one NaN cell can discard most of a table.

Boosting keeps improving on its own training rows after it has stopped improving on unseen data, so the number of trees needs a limit that comes from the data. Early stopping holds back part of the training rows as a validation set and ends training once the score on that set stops improving. A separate test split stays outside both fitting and validation, so its metrics describe rows the model never saw.

Steps to train a gradient boosting classifier with scikit-learn:

  1. Install scikit-learn and pandas in your project's virtual environment.
    $ python -m pip install scikit-learn pandas

    Tested with scikit-learn 1.9.1, pandas 3.1.1, and Python 3.12 on Linux. scikit-learn 1.9.1 requires Python 3.11 or newer. pandas holds the feature table and counts its NaN cells.
    Related: How to install scikit-learn on Ubuntu or Debian

  2. Create a file named train_gradient_boosting.py in your project directory using your text editor.
  3. Enter the following imports, table loading, and held-out split.
    train_gradient_boosting.py
    import numpy as np
    from sklearn.datasets import load_breast_cancer
    from sklearn.ensemble import HistGradientBoostingClassifier
    from sklearn.metrics import (
        accuracy_score, classification_report
    )
    from sklearn.model_selection import train_test_split
     
    data = load_breast_cancer(as_frame=True)
    rng = np.random.default_rng(42)
    X = data.data.mask(rng.random(data.data.shape) < 0.1)
    y = data.target.map(dict(enumerate(data.target_names)))
     
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, stratify=y, random_state=42
    )

    load_breast_cancer ships with scikit-learn and holds 569 rows of 30 numeric features with two classes. Its cells are complete, so mask blanks about 10 percent of them at random to stand in for gaps in real records. With your own table, set X to a pandas DataFrame of its numeric feature columns and y to its label column instead.

  4. Add the missing-value report at the end of train_gradient_boosting.py.
    def show_missing(stage):
        frames = {"training": X_train, "held-out": X_test}
        for name, rows in frames.items():
            print(
                f"{stage}, {name}: {len(rows)} rows, "
                f"{rows.isna().any(axis=1).sum()} with NaN, "
                f"{rows.isna().sum().sum()} NaN cells"
            )
     
     
    show_missing("before fit")
  5. Add the classifier settings at the end of the file.
    model = HistGradientBoostingClassifier(
        learning_rate=0.05,
        max_iter=1000,
        early_stopping=True,
        validation_fraction=0.15,
        n_iter_no_change=20,
        random_state=42,
    )

    max_iter is the upper limit on boosting rounds. validation_fraction holds back 15 percent of the training rows, and n_iter_no_change ends training after 20 rounds without a better score on those rows. random_state fixes which rows are held back, so a different seed can stop at a different round.

    A table this small needs early_stopping=True. The default auto value turns early stopping on above 10,000 rows, so these 455 rows would run all 1,000 rounds and leave validation_score_ empty.

  6. Add the fitting call and a second missing-value report at the end of the file.
    model.fit(X_train, y_train)
    show_missing("after fit")

    fit receives X_train with its NaN cells and no imputer. The validation rows come from inside X_train, so X_test stays out of both fitting and early stopping.

  7. Add the held-out predictions and metrics at the end of the file.
    predictions = model.predict(X_test)
    print("first predictions:", *predictions[:3])
    accuracy = accuracy_score(y_test, predictions)
    print(f"held-out accuracy: {accuracy:.3f}")
    has_nan = X_test.isna().any(axis=1)
    nan_accuracy = accuracy_score(
        y_test[has_nan], predictions[has_nan]
    )
    print(f"accuracy on rows with NaN: {nan_accuracy:.3f}")
    print(classification_report(y_test, predictions))

    has_nan selects the held-out rows with at least one NaN cell, so the second accuracy line scores only rows that LogisticRegression would refuse.

  8. Save train_gradient_boosting.py.
  9. Run the script to train the classifier and score the held-out rows.
    $ python train_gradient_boosting.py
    before fit, training: 455 rows, 430 with NaN, 1333 NaN cells
    before fit, held-out: 114 rows, 107 with NaN, 320 NaN cells
    after fit, training: 455 rows, 430 with NaN, 1333 NaN cells
    after fit, held-out: 114 rows, 107 with NaN, 320 NaN cells
    first predictions: benign malignant benign
    held-out accuracy: 0.982
    accuracy on rows with NaN: 0.981
                  precision    recall  f1-score   support
    
          benign       0.97      1.00      0.99        72
       malignant       1.00      0.95      0.98        42
    
        accuracy                           0.98       114
       macro avg       0.99      0.98      0.98       114
    weighted avg       0.98      0.98      0.98       114

    Only 25 of the 455 training rows are complete, so dropna() would leave almost nothing to train on. The after fit counts match the before fit counts because fit leaves X_train unchanged. The report covers all 114 held-out rows, and 107 of them have at least one NaN cell.

  10. Open train_gradient_boosting.py in your text editor.
  11. Add the early-stopping diagnostics at the end of the file.
    loss = -model.validation_score_
    print(f"early stopping used: {model.do_early_stopping_}")
    print(f"n_iter_: {model.n_iter_} of max_iter {model.max_iter}")
    print(f"best validation round: {loss.argmin()}")
    print(f"validation log loss at best: {loss.min():.3f}")
    print(f"validation log loss at end: {loss[-1]:.3f}")

    validation_score_ stores the score before the first round at index 0 and then one score per round, so each index is a round number. With the default loss scoring it holds negative log loss, and the minus sign turns it back into a loss where lower is better.

  12. Save train_gradient_boosting.py.
  13. Run the script again to confirm that early stopping ended training before max_iter.
    $ python train_gradient_boosting.py
    ##### snipped #####
    early stopping used: True
    n_iter_: 131 of max_iter 1000
    best validation round: 111
    validation log loss at best: 0.078
    validation log loss at end: 0.080

    Training stopped at round 131, which is 20 rounds after the best validation loss at round 111. The fitted model keeps all 131 rounds, including the last 20. When n_iter_ equals max_iter, training reached the limit before early stopping could end it.

Share this guide