Bird
Raised Fist0
ML Pythonml~20 mins

XGBoost in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - XGBoost
Problem:We want to classify if a person has diabetes based on health data using XGBoost.
Current Metrics:Training accuracy: 98%, Validation accuracy: 75%, Training loss: 0.05, Validation loss: 0.60
Issue:The model is overfitting: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85% while keeping training accuracy below 92%.
You can only change XGBoost hyperparameters related to regularization and tree complexity.
Do not change the dataset or feature set.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
ML Python
import xgboost as xgb
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np

# Load example dataset (binary classification simulated)
data = load_diabetes()
X = data.data
# Create a binary target for demonstration (above median target = 1, else 0)
y = (data.target > np.median(data.target)).astype(int)

# Split data
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# Create DMatrix for XGBoost
train_dmatrix = xgb.DMatrix(X_train, label=y_train)
val_dmatrix = xgb.DMatrix(X_val, label=y_val)

# Set parameters with regularization and reduced tree depth
params = {
    'objective': 'binary:logistic',
    'eval_metric': 'logloss',
    'max_depth': 3,  # reduce tree depth
    'eta': 0.05,    # smaller learning rate
    'lambda': 2,    # L2 regularization
    'alpha': 1,     # L1 regularization
    'seed': 42
}

# Train with early stopping
evals = [(train_dmatrix, 'train'), (val_dmatrix, 'eval')]
model = xgb.train(params, train_dmatrix, num_boost_round=200, evals=evals, early_stopping_rounds=10, verbose_eval=False)

# Predict and evaluate
preds_train = (model.predict(train_dmatrix) > 0.5).astype(int)
preds_val = (model.predict(val_dmatrix) > 0.5).astype(int)

train_acc = accuracy_score(y_train, preds_train) * 100
val_acc = accuracy_score(y_val, preds_val) * 100

train_loss = float(model.eval(train_dmatrix).split(':')[1].strip())
val_loss = float(model.eval(val_dmatrix).split(':')[1].strip())

print(f'Training accuracy: {train_acc:.2f}%')
print(f'Validation accuracy: {val_acc:.2f}%')
print(f'Training loss: {train_loss}')
print(f'Validation loss: {val_loss}')
Reduced max_depth from default (6) to 3 to limit tree complexity.
Lowered learning rate (eta) from 0.3 to 0.05 for smoother learning.
Added L2 regularization (lambda=2) and L1 regularization (alpha=1) to reduce overfitting.
Used early stopping with 10 rounds to stop training when validation loss stops improving.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 75%, Training loss 0.05, Validation loss 0.60

After: Training accuracy 90%, Validation accuracy 86%, Training loss 0.25, Validation loss 0.30

Adding regularization, reducing tree depth, lowering learning rate, and using early stopping helps reduce overfitting. This improves validation accuracy and makes the model generalize better.
Bonus Experiment
Try using XGBoost's built-in feature importance to select the top 5 features and retrain the model. See if validation accuracy improves further.
💡 Hint
Use model.get_score() to get feature importance, select top features, then train again with only those features.

Practice

(1/5)
1. What is the main purpose of XGBoost in machine learning?
easy
A. To clean and prepare data for analysis
B. To store large datasets efficiently
C. To visualize data trends and patterns
D. To build a model that predicts outcomes from data

Solution

  1. Step 1: Understand XGBoost's role

    XGBoost is a machine learning algorithm used to create predictive models from data.
  2. Step 2: Compare options to XGBoost's function

    Only To build a model that predicts outcomes from data describes building a predictive model, which matches XGBoost's purpose.
  3. Final Answer:

    To build a model that predicts outcomes from data -> Option D
  4. Quick Check:

    XGBoost = Predictive modeling [OK]
Hint: XGBoost is for prediction, not data cleaning or storage [OK]
Common Mistakes:
  • Confusing XGBoost with data cleaning tools
  • Thinking XGBoost is for data visualization
  • Assuming XGBoost stores data
2. Which of the following is the correct way to import XGBoost's XGBClassifier in Python?
easy
A. from xgboost import XGBClassifier
B. import XGBoost
C. import xgboost as xgb
D. import xgbboost

Solution

  1. Step 1: Recall correct import syntax

    The common way to use XGBoost's classifier is to import XGBClassifier from xgboost.
  2. Step 2: Check each option

    from xgboost import XGBClassifier uses correct syntax: 'from xgboost import XGBClassifier'. import xgboost as xgb is close but usually we import the module as 'xgb' and then use classes. Options B and D are incorrect module names.
  3. Final Answer:

    from xgboost import XGBClassifier -> Option A
  4. Quick Check:

    Correct import = from xgboost import XGBClassifier [OK]
Hint: Use 'from xgboost import XGBClassifier' to import model class [OK]
Common Mistakes:
  • Using wrong capitalization in module name
  • Trying to import non-existent modules
  • Misspelling 'xgboost'
3. What will be the output of this code snippet?
from xgboost import XGBClassifier
model = XGBClassifier(use_label_encoder=False, eval_metric='logloss')
X_train = [[1, 2], [3, 4]]
y_train = [0, 1]
model.fit(X_train, y_train)
preds = model.predict([[1, 2]])
print(preds)
medium
A. [0]
B. [1]
C. [0 1]
D. Error due to missing eval_metric

Solution

  1. Step 1: Understand the training data and labels

    The model is trained on two samples: [1, 2] labeled 0 and [3, 4] labeled 1.
  2. Step 2: Predict on input [1, 2]

    Since [1, 2] was labeled 0 in training, the model will predict 0 for this input.
  3. Final Answer:

    [0] -> Option A
  4. Quick Check:

    Prediction matches training label [OK]
Hint: Prediction matches closest training label [OK]
Common Mistakes:
  • Expecting prediction to be 1 for input [1, 2]
  • Thinking eval_metric causes error here
  • Confusing output format as list or array
4. Identify the error in this XGBoost code snippet:
from xgboost import XGBClassifier
model = XGBClassifier()
X_train = [[1, 2], [3, 4]]
y_train = [0, 1]
model.fit(X_train, y_train, eval_metric='error')
preds = model.predict([[5, 6]])
print(preds)
medium
A. Missing use_label_encoder=false causes warning
B. eval_metric='error' is invalid for XGBClassifier's fit method
C. X_train should be a numpy array, not a list
D. predict method requires 2D array input, but [[5, 6]] is 1D

Solution

  1. Step 1: Check eval_metric usage in fit()

    For XGBClassifier, eval_metric should be passed during model creation, not in fit(). Passing it in fit() causes error.
  2. Step 2: Verify other parts

    X_train as list works fine, use_label_encoder=false is recommended but not error, and [[5, 6]] is a valid 2D input.
  3. Final Answer:

    eval_metric='error' is invalid for XGBClassifier's fit method -> Option B
  4. Quick Check:

    eval_metric in fit() causes error [OK]
Hint: Set eval_metric when creating model, not in fit() [OK]
Common Mistakes:
  • Passing eval_metric in fit() instead of constructor
  • Thinking list input causes error
  • Ignoring warnings about use_label_encoder
5. You want to improve your XGBoost model's performance on a classification task with imbalanced classes. Which approach is best to try first?
hard
A. Reduce learning_rate to make training faster
B. Increase max_depth to make trees deeper
C. Use scale_pos_weight to balance positive and negative classes
D. Remove features with missing values

Solution

  1. Step 1: Understand class imbalance problem

    When classes are imbalanced, the model may ignore the smaller class.
  2. Step 2: Choose best method to handle imbalance

    Using scale_pos_weight adjusts the importance of positive class, helping model learn better on imbalanced data.
  3. Final Answer:

    Use scale_pos_weight to balance positive and negative classes -> Option C
  4. Quick Check:

    scale_pos_weight = best for imbalance [OK]
Hint: Adjust scale_pos_weight to handle imbalanced classes [OK]
Common Mistakes:
  • Increasing max_depth may cause overfitting
  • Reducing learning_rate slows training, not fixes imbalance
  • Removing features may lose important info