How to use XGBoost algorithm for regression in R?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
XGBoost (eXtreme Gradient Boosting) is one of the most effective algorithms for regression tasks, offering regularization, handling of missing values, and parallel tree construction. In R, the xgboost package provides the xgb.train() and xgboost() functions. For regression, set objective = "reg:squarederror" (MSE loss) or "reg:squaredlogerror" (log-transformed MSE). The workflow involves converting data to xgb.DMatrix, tuning hyperparameters with cross-validation (xgb.cv), training the model, and evaluating with RMSE or MAE.
Installation and Setup
Basic Regression Example
The objective = "reg:squarederror" parameter tells XGBoost to minimize mean squared error, making it a standard regression model.
Cross-Validation for Hyperparameter Tuning
xgb.cv performs k-fold cross-validation and reports train/test metrics per round. early_stopping_rounds prevents overfitting by stopping when the test metric plateaus.
Grid Search for Hyperparameters
Feature Importance
Gain measures the improvement in accuracy contributed by a feature. Cover measures the relative number of observations related to a feature. Frequency counts how often a feature appears in trees.
Regression Objective Functions
Complete Workflow with caret
The caret package wraps XGBoost with a unified interface, handling data conversion, cross-validation, and grid search automatically.
Common Pitfalls
- Not using
xgb.DMatrix: Passing a raw data frame toxgb.trainfails. XGBoost requires numeric matrices wrapped inxgb.DMatrix. Convert factors to numeric (one-hot encoding) and useas.matrix()before creating the DMatrix. - Overfitting without early stopping: XGBoost can memorize training data if
nroundsis too high. Always usexgb.cvwithearly_stopping_roundsto find the optimal number of boosting rounds, or use a validation set in thewatchlist. - Using deprecated
reg:linearobjective: The objective"reg:linear"was renamed to"reg:squarederror"in XGBoost 0.90. Using the old name triggers a deprecation warning. Always use"reg:squarederror"for standard regression. - Ignoring feature importance for sparse features: XGBoost handles sparse data well, but including thousands of irrelevant features still slows training. Use feature importance after an initial model to select the top features and retrain.
- Not scaling the learning rate with nrounds: A high
eta(0.3) with many rounds overfits quickly. A loweta(0.01) with few rounds underfits. The rule of thumb is to loweretaand increasenroundswith early stopping for best results.
Summary
- Use
objective = "reg:squarederror"for standard regression in XGBoost - Convert data to
xgb.DMatrixwith numeric matrices before training - Use
xgb.cvwithearly_stopping_roundsto find optimalnroundsand prevent overfitting - Tune
eta,max_depth,subsample, andcolsample_bytreevia grid search - Check
xgb.importance()to understand which features drive predictions - Use
caret::train(method = "xgbTree")for an integrated workflow with automatic cross-validation
Related reading
- How to visualize a tensor summary in tensorboard
- How to visualize a TFRecord?
- How to visualize learned filters on tensorflow
- How to work with Tensorflow on Android platform?
- How to view Apache Parquet file in Windows?
- How to view the plain text format of the row based binarly logs
- How to work with TF Lite library in a c project
- How to wrap a custom TensorFlow loss function in Keras?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.