Hands-On: Train a Model with XGBoost

Train a classifier on a CSV in S3 using the built-in XGBoost algorithm.

1 min read

XGBoost is a popular, fast algorithm for tabular data: yes/no predictions, scores, and categories. SageMaker AI provides it as a ready-made container. For the built-in CSV format, the first column is the label (e.g. 1 = churned) and there's no header row.

Run this from a SageMaker Studio notebook, where the execution role and SDK are already set up:

Try it

train.ipynb
import sagemaker
from sagemaker import image_uris
from sagemaker.estimator import Estimator
from sagemaker.inputs import TrainingInput

session = sagemaker.Session()
role = sagemaker.get_execution_role()
bucket = session.default_bucket()

image = image_uris.retrieve("xgboost", region=session.boto_region_name, version="1.7-1")

estimator = Estimator(
    image_uri=image,
    role=role,
    instance_count=1,
    instance_type="ml.m5.large",
    output_path=f"s3://{bucket}/churn/model",
    use_spot_instances=True,  # use spare capacity for cheaper training
    max_run=1800,             # max training seconds
    max_wait=3600,            # max total seconds, including waiting for Spot
)
estimator.set_hyperparameters(objective="binary:logistic", num_round=100, max_depth=5)

estimator.fit({
    "train": TrainingInput(f"s3://{bucket}/churn/train.csv", content_type="text/csv"),
    "validation": TrainingInput(f"s3://{bucket}/churn/validation.csv", content_type="text/csv"),
})

What happened

  • image_uris.retrieve found the right XGBoost container for your Region.
  • fit started a training job: SageMaker launched an instance, trained, saved the model to output_path, and shut down.
  • Managed Spot Training used spare capacity, so you paid for far fewer seconds.
Note

This uses the classic Estimator API of the SageMaker Python SDK. Newer SDK versions also offer other interfaces, so check the SDK documentation for the version you install.

Key takeaways

  • Built-in algorithms like XGBoost run from AWS-provided containers.
  • estimator.fit() runs a managed training job and saves the model to S3.
  • Managed Spot Training can cut training costs significantly.

Check your understanding

Pick an answer to see the explanation.

  1. 1. For SageMaker's built-in XGBoost with CSV input, where does the label go?