AI & Machine Learning Master Course — 075. Gradient boosting for tabular data
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 075: Gradient boosting for tabular data
Prerequisites: Lesson 074. Learning outcome: Fit and validate gradient-boosted tree models on mixed features.
1. Combine a capable estimator with disciplined data preparation
Gradient-boosted trees are useful candidates for tabular prediction because additive trees can model nonlinearities and feature interactions. That flexibility does not remove the need for a schema, prediction-time availability, careful categorical representation, or honest evaluation. A powerful estimator can exploit leaked information more effectively than a weak one.
This lab predicts a synthetic handling duration from parcel mass and route category. The target-generating formula is nonlinear in mass and includes route effects plus noise. Some observed masses are missing. The formula is deliberately simple enough to learn, so the experiment checks a workflow rather than establishing performance on real logistics data.
2. Prepare mixed features within the evaluated pipeline
The numerical branch imputes missing mass using the training median and adds a missingness indicator. The categorical branch one-hot encodes route labels local, regional, remote, with an all-zero policy for unfamiliar categories. ColumnTransformer combines these branches before GradientBoostingRegressor.
Imputation statistics and the category vocabulary are learned separately inside each cross-validation training fold. Ordinary numerical standardization is not necessary for this threshold-tree example, but correct data types and consistent transformation remain essential. Dense one-hot output is acceptable here because there are only three categories; high-cardinality data need a deliberate memory and representation plan.
Missingness can carry process information, but an indicator does not make that process stable. If a future measurement system changes when mass is absent, the learned association may fail. Likewise, the unknown-route fallback defines a computable input vector without establishing that an unfamiliar island route behaves like any known route.

3. Choose a bounded set of regularization settings
The candidate model uses sixty boosting stages, learning rate 0.1, and depth-two trees. Development cross-validation compares minimum leaf sizes three and eight using MAE. These settings are declared before final assessment rather than expanded after seeing which test cases are difficult.
Learning rate, stage count, tree complexity, and minimum leaf size interact. Increasing depth can capture interactions but may increase variance; smaller steps often require more stages. The correct settings depend on the amount and quality of data. No fixed small grid proves the globally optimal configuration.
Early stopping is another development choice. If an implementation creates an internal random validation split, check whether that respects groups and time. For a chronological task, an automatically shuffled stopping set may answer the wrong question. The current example uses a fixed stage count and no early-stopping selection, avoiding that additional boundary in this small lab.
4. Understand the histogram-based alternative
Histogram gradient boosting groups numerical values into bins and searches over binned representations, which can be more efficient on larger tabular datasets. Scikit-learn's histogram estimator also offers native missing-value handling and categorical support under documented input and version requirements. Those features differ from assuming every tree implementation accepts arbitrary raw strings or missing values.
A histogram method introduces its own controls, including bin count, leaf complexity, and regularization. Binning can change the set of available splits, so it is not merely a faster identical implementation in every detail. Benchmark predictive quality and resource use on representative data before choosing a variant.
This lesson executes the explicit imputation-and-encoding classic booster. The histogram alternative is explained as another documented option, not claimed to have been run or compared in the printed results.
5. Report the frozen test and fallback behavior
The generated dataset has 240 rows; 180 form development data and sixty are reserved for final assessment. Three-fold development validation selects leaf size three, with mean MAE about 2.1328. Final model MAE is 2.7405, compared with 13.0229 for a median-target baseline fitted on development labels.
The sizable improvement is expected in a designed dataset with strong nonlinear signal. It does not establish real-world usefulness or superiority over other strong models that were not compared. Report the generator, split, candidate set, and metric rather than presenting the number as a general tabular benchmark.
A separate input with mass three and unknown route island receives prediction about 11.0932. Its true outcome is not supplied, so this only checks that the declared fallback executes. It is not evidence of accurate predictions for unseen routes. Monitor unknown categories and define when unsupported inputs should be reviewed or rejected.
CPU lab: fit and evaluate the complete mixed-data system
The script uses local NumPy and scikit-learn, checked with versions 2.3.5 and 1.8.0. No download, credentials, or GPU is needed. The search performs six fold fits and one refit. Feature construction keeps numeric missing values as actual NaN values rather than string labels.
The final test does not influence imputation, encoding, leaf-size selection, or baseline fitting. Once its results are read, any redesign would need appropriately independent assessment. Save the complete fitted pipeline and input schema together so future predictions cannot silently bypass the learned preprocessing.
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import train_test_split,KFold,GridSearchCV
from sklearn.metrics import mean_absolute_error
rng=np.random.default_rng(75)
mass=rng.uniform(1,8,240);route=rng.choice(['local','regional','remote'],240)
effect=np.array([{'local':0,'regional':3,'remote':8}[r] for r in route])
y=2+.7*mass**2+effect+rng.normal(scale=1,size=240)
observed=mass.copy();observed[rng.random(240)<.1]=np.nan
X=np.empty((240,2),dtype=object)
X[:,0]=observed;X[:,1]=route
xt,xs,yt,ys=train_test_split(X,y,test_size=.25,random_state=75)
prep=ColumnTransformer([('mass',SimpleImputer(strategy='median',add_indicator=True),[0]),
('route',OneHotEncoder(handle_unknown='ignore',sparse_output=False),[1])])
pipe=Pipeline([('prep',prep),('boost',GradientBoostingRegressor(learning_rate=.1,max_depth=2,
n_estimators=60,random_state=75))])
search=GridSearchCV(pipe,{'boost__min_samples_leaf':[3,8]},
cv=KFold(3,shuffle=True,random_state=75),scoring='neg_mean_absolute_error',n_jobs=1).fit(xt,yt)
pred=search.predict(xs)
base=DummyRegressor(strategy='median').fit(xt,yt).predict(xs)
print('Selected leaf size:',search.best_params_['boost__min_samples_leaf'])
print('Development CV MAE:',round(-search.best_score_,4))
print('Test MAE model/baseline:',round(mean_absolute_error(ys,pred),4),round(mean_absolute_error(ys,base),4))
print('Unknown-route prediction:',search.predict([[3.,'island']]).round(4).tolist())
Four practice questions with worked answers
Practice 1
Why put the median imputer inside the searched pipeline rather than fitting it once beforehand?
Answer: Each validation fold must be predicted using a median learned without its rows. Fitting the imputer globally would let held-out feature values influence the representation. The final selected pipeline can then be refitted on all development data before applying its frozen transformation to the final test.
Practice 2
The candidate grid has two leaf sizes and three folds. How many fits occur with one final refit?
Answer: There are 2×3=6 cross-validation fits plus one refit, for seven. Each fitted booster internally builds sixty sequential trees. Count both the outer search and the estimator’s internal work when planning memory and execution time.
Practice 3
An unknown route receives a numerical prediction without error. What has been established?
Answer: The preprocessing fallback and prediction path are executable for that input. Accuracy and operational suitability remain untested because no representative outcome evidence was supplied. An all-zero category block is a software policy, not a validated semantic model of the unfamiliar route.
Practice 4
Why might automatic random early stopping be unsuitable for forecasting?
Answer: It can mix future and past rows or use labels unavailable at a forecast origin. The stopping decision then violates the intended temporal boundary. Choose explicit time-respecting development partitions and account for label delays rather than assuming an internal split matches the task.
Five multiple-choice questions
Question 1
What does the candidate search vary in this lab?
- A. The final-test target values
- B. Minimum leaf size
- C. The route-label definitions
Correct: B. Other listed boosting settings stay fixed during the two-candidate comparison.
Question 2
Why is dense one-hot output acceptable in this particular example?
- A. Only three route categories make the representation small
- B. Dense matrices are always required for every booster
- C. Encoding removes all memory costs
Correct: A. The choice is justified by the tiny category set, not a universal rule for tabular data.
Question 3
What changes with histogram-based split search?
- A. The need for held-out evaluation disappears
- B. Candidate numerical splits are represented through bins
- C. All raw categories become ordered measurements
Correct: B. Binning affects search efficiency and available split resolution while leaving evaluation discipline necessary.
Question 4
What is the correct interpretation of the island prediction?
- A. A calibrated confidence interval
- B. Proof of generalization to every new route
- C. A fallback execution check without accuracy evidence
Correct: C. A numerical output alone cannot establish performance on an unsupported category.
Question 5
Where is the median baseline’s constant learned?
- A. From development targets
- B. From the unknown-route example
- C. From the final-test targets
Correct: A. The comparator must respect the same information boundary as the selected model.
Common pitfalls
Do not assume native categorical and missing-value support is identical across boosting packages or versions. Do not fit preprocessing outside development folds, use random stopping splits blindly, or confuse successful fallback execution with reliable unfamiliar-category predictions.
Summary
Gradient boosting can model rich tabular relationships when paired with disciplined preprocessing and bounded selection. Compare against a legitimate baseline, understand implementation-specific features, and keep test results and fallback checks within their actual evidential scope.