smartyfy.mrindigi.com

AI & Machine Learning Master Course — 076. Histogram boosting and missing values

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 076: Histogram boosting and missing values

Prerequisites: Lesson 075. Learning outcome: Explain histogram approximations and estimator-specific missing-value behavior.

Why approximate split search?

A boosting model can spend much of its training effort asking where to split numeric columns. A feature with thousands of distinct values offers many candidate boundaries. Histogram boosting compresses nearby observed values into bins and evaluates boundaries between bins. The model still learns a sequence of trees correcting its current predictions; the approximation changes which splits are considered.

Imagine eight ordered measurements, 1 through 8. An exact threshold search can distinguish seven boundaries. If an illustrative binning rule groups them into four pairs, only three boundaries remain. A threshold between 3 and 4 is unavailable because both belong to the same bin. This deliberately simple rule explains the trade-off; the library learns its own bin thresholds rather than using our paired grouping.

Binning is learned from the fitting data. Validation values are mapped using those learned thresholds. Choosing bins after inspecting a final test distribution would change the experiment, even if its targets were hidden. More bins provide finer resolution but can increase work and flexibility. Fewer bins are not automatically better regularization for every dataset.

Two aligned number lines show values 1 through 8. Seven exact midpoint boundaries become three boundaries after illustrative grouping into pairs [1, 2], [3, 4], [5, 6], [7, 8]. The 3–4 boundary is unavailable inside its bin. A note distinguishes NaN routing from numeric zero or imputation.
Binning reduces split resolution. These paired bins explain the trade-off and are not claimed to be the library’s learned thresholds. Open full-size diagram

Missingness becomes a routing decision

NaN represents an unavailable numeric measurement, not zero. A histogram tree can compare sending missing observations left versus right while choosing a split. Later missing observations follow the learned direction. This is a fitted predictive rule, not a reconstruction of the unobserved value.

Consider a sensor that fails more often under heavy load. Missingness may then predict the target. A model can exploit that association without knowing the missing reading. If technicians later replace the sensor, the failure mechanism changes and the old association may disappear. Native missing-value support solves an execution problem; it does not establish that missingness is harmless or stable.

For this estimator, if a feature had no missing observations during training, prediction-time missing values follow the child containing more training samples. That fallback has no special knowledge of why the new value is absent. Monitor missingness rates, inspect affected slices, and define a fallback when essential measurements disappear.

Keep controls and data types explicit

This lesson uses HistGradientBoostingRegressor with numeric arrays and no categorical features. Its max_iter controls boosting iterations. max_leaf_nodes and min_samples_leaf restrict individual trees. max_bins controls the non-missing numeric bin budget; missing values use a separate bin. Check the installed version before copying examples using native categorical handling, whose dtype conventions and defaults have evolved.

We disable automatic early stopping so the small example has a clear, fixed training protocol. A real early-stopping experiment needs a development validation subset, never the final test set. With grouped or temporal observations, an internal random split may answer the wrong question. Design an appropriate stopping split or select a fixed iteration count inside an appropriate outer procedure.

The model can tolerate some NaNs but cannot infer the meaning of arbitrary text, inconsistent units, or a column silently shifted into the wrong position. Preserve a schema with names, types, missing-value conventions, and admissible ranges. A valid floating-point array is necessary but insufficient evidence of a valid prediction request.

CPU lab: numerical data with missing readings

The following standalone CPU experiment creates a quadratic relationship, then independently hides about ten percent of feature entries. There are 180 fitting rows and 60 development validation rows. NumPy, scikit-learn, and its threadpoolctl dependency are sufficient; no download, GPU, or account is needed. It was executed with scikit-learn 1.8.0.

The observed validation MAE is 1.0048 target units. Two probes with missing inputs produce finite predictions, approximately 3.4762 and 0.1173. These probes test supported execution, not accuracy: we have no observed targets for them. Some information was destroyed by hiding features, so the task is genuinely harder than merely evaluating the original complete measurements.

import os
os.environ.setdefault("LOKY_MAX_CPU_COUNT", "1")
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from threadpoolctl import threadpool_limits
rng = np.random.default_rng(76)
X = rng.uniform(-2, 2, (240, 2))
y = 3 * X[:, 0] ** 2 + X[:, 1] + rng.normal(0, .2, 240)
X[rng.random(X.shape) < .1] = np.nan
Xt, Xv, yt, yv = train_test_split(X, y, test_size=60, random_state=76)
with threadpool_limits(limits=1):
    model = HistGradientBoostingRegressor(max_iter=60, max_bins=32,
        max_leaf_nodes=7, min_samples_leaf=8, early_stopping=False,
        random_state=76).fit(Xt, yt)
    pred = model.predict(Xv)
    print('validation MAE', round(mean_absolute_error(yv, pred), 4))
    print('missing probes', np.round(model.predict([[np.nan, 0], [0, np.nan]]), 4))
assert np.isfinite(pred).all()
print('training rows', len(Xt), 'validation rows', len(Xv))

Read the result as a limited experiment

The dataset has a deliberately stable random missingness mechanism and only two features. Neither condition represents every sensor system. To compare native routing with median imputation, reserve the same development folds, fit each imputer inside each fold, and select using a predefined metric. Include performance on missing and complete cases separately, with sample counts.

A small CPU example also cannot establish a speed advantage at production scale. Report measured training time and peak memory on the intended workload before making an efficiency claim. Record the thread budget because histogram boosting uses lower-level parallelism. The environment setting in the example simply limits joblib's reported CPU budget; threadpool_limits controls the numerical thread pools during fitting.

Four practice questions with worked answers

Practice 1

Eight distinct values are grouped into four ordered nonempty bins. How many between-bin boundaries remain?

Answer: Four bins have three internal boundaries, compared with seven between eight distinct values. This counts candidate positions only; the actual training algorithm also applies leaf-size and other validity constraints.

Practice 2

A missing measurement is replaced with zero before native-missing training. What information changes?

Answer: The model can no longer distinguish a genuine zero from an absent measurement unless an additional indicator preserves that distinction. Retaining NaN lets this estimator learn missing-value routing directly.

Practice 3

Training has no missing values for a feature. What does this estimator do with a later missing value?

Answer: At a split on that feature it sends the observation to the child with more fitting samples. This documented fallback is not an estimate of the missing measurement or a reliability guarantee.

Practice 4

A complete-case MAE is 0.8 across 40 cases and a missing-case MAE is 1.4 across 20. Compute overall MAE.

Answer: The weighted total absolute error is 40 × 0.8 + 20 × 1.4 = 60. Dividing by all 60 cases gives MAE 1.0. Averaging the two slice means equally would incorrectly give 1.1.

Five multiple-choice questions

Question 1

What does histogram binning approximate?

  • A. The number of target labels observed
  • B. The final test targets used for stopping
  • C. The set of candidate numeric split positions

Correct: C. Nearby feature values share bins, reducing available split positions. Target labels and test-set access are separate issues.

Question 2

What does a native missing branch learn?

  • A. A direction that can improve the training objective
  • B. The exact unobserved numerical value
  • C. A proof that the missingness mechanism is random

Correct: A. Routing is optimized from observed training evidence; it neither imputes the true value nor identifies the missingness mechanism.

Question 3

Where should early stopping obtain feedback?

  • A. Only the prediction-time batch
  • B. An appropriate development validation subset
  • C. The final test set after every iteration

Correct: B. Stopping selects model complexity, so its feedback belongs within development.

Question 4

What do finite predictions for missing probes establish?

  • A. The missingness association will remain stable
  • B. The fitted pipeline accepts those inputs
  • C. The probes have small prediction errors

Correct: B. Without probe targets we establish execution behavior, not accuracy or stability.

Question 5

Why inspect the installed version for categorical inputs?

  • A. Numeric binning eliminates all schema requirements
  • B. Every version requires the same manual encoding
  • C. Supported conventions and defaults may differ

Correct: C. Version-specific dtype and parameter behavior matters; a schema remains necessary.

Common pitfalls

Do not translate every missing value to zero without considering its meaning. Do not use a final test set to choose bins or stopping iterations. Avoid assuming a missingness signal survives changes in data collection. Native support applies to specific estimators, not automatically to every transformer in a pipeline.

Summary

Histogram boosting trades finer split resolution for a compact search. Missing observations follow learned or documented fallback routes. Evaluate the whole procedure with appropriate development boundaries and monitor the collection process that creates missing values.

Primary sources and further reading