Examples · Compiling
monotone_constraints
Declare per-feature directions, train the constrained backend, and read the build-time verification that the quantized trees actually obey them.
Code#
monotone_constraints.py
import numpy as np from _setup import X_train, bands, feature_names, teacher_scores, y_train from compileml.artifact import build_artifactfrom compileml.compile import train_whitebox, verify_monotone_constraints # Repayment status rises with delinquency, so risk should rise with it. A# larger approved limit should not increase risk. Directions are policy# statements about the model, and the artifact carries them.constraints = {"PAY_1": +1, "PAY_2": +1, "LIMIT_BAL": -1} # X_train is a plain array, so it carries no column names: train_whitebox# needs indices. build_artifact is given feature_names, so it accepts the# names directly.by_index = {feature_names.index(name): sign for name, sign in constraints.items()} whitebox, _ = train_whitebox(X_train, teacher_scores, monotone_constraints=by_index)latent = whitebox.predict(X_train).clip(0, 1) artifact = build_artifact( whitebox, feature_names, baseline=np.median(X_train, axis=0), band_edges=bands, calibration_latent=latent, calibration_y=y_train, monotone_constraints=constraints,) report = verify_monotone_constraints(artifact["model"], artifact["model"]["monotone_constraints"])print("declared:", constraints)print("verified against the quantized trees:", report)Output#
Captured from an actual run against compileml 0.9.0 and the UCI credit panel. If this script stops working, the build fails.
captured in CImonotone_constraints.py
declared: {'PAY_1': 1, 'PAY_2': 1, 'LIMIT_BAL': -1}verified against the quantized trees: {'ok': True, 'n_violations': 0, 'violations': [], 'method': 'per_tree'}Notes#
- Any nonzero sign switches training to HistGradientBoostingRegressor; all-zero or None keeps the classic GradientBoostingRegressor.
- Verification is exact at any depth: a tree touches at most `depth` features, so its cell grid is tiny.
- At depth ≤ 2, scorecard_monotone_report() certifies the printed tables themselves — a validator can repeat it in a spreadsheet.