AWS Unmapped logoAWS Sin Mapa
AWS BUILDER

Training a classification model with Amazon SageMaker AI

Train an XGBoost classifier with Amazon SageMaker AI (SDK v3): data in S3, a training job, an endpoint and how to read the confusion matrix beyond accuracy.

AWS Unmapped14 min read

Training a machine learning model on your laptop is relatively simple. The hard part starts afterwards: how you train it on a machine that isn’t yours, where you store the result, how you turn it into a service another application can query and, above all, how you know whether its answers can be trusted. Amazon SageMaker AI solves the first three questions. The fourth one is up to you.

In this article we build a classification model with Amazon SageMaker AI end to end: we prepare the data, train with the built-in XGBoost algorithm using the SageMaker Python SDK v3, deploy the model to an endpoint, ask it for predictions and evaluate them with a confusion matrix. All the code comes from a lab I tested in full in SageMaker Studio, in the us-east-1 Region, on November 13, 2026, with the sagemaker SDK 3.29.0. The results and errors you will see are the ones from that test.

The use case is a supervised learning classic: from 30 measurements of a biopsy, predict whether a tumor is malignant or benign. It’s an educational exercise, not a diagnostic tool, but it has one virtue: it makes it very clear why a high percentage of correct answers isn’t enough to decide whether a model is useful.

What you will build

The flow has five pieces. The data lives in Amazon S3. A SageMaker AI training job reads that data, trains the model on a managed instance and leaves the result, a model.tar.gz file, back in S3. With that artifact you create an endpoint: an instance that loads the model and answers HTTPS requests. Finally, the notebook sends new data to the endpoint and receives a probability per patient.

Flow diagram: data in S3, training job with XGBoost, model.tar.gz, Model plus EndpointConfig plus Endpoint, and predictions. Training is billed by the second; the endpoint charges by the hour while it’s running.

Training shuts itself down when it finishes; the endpoint doesn’t. That difference decides almost the entire cost of the lab.

Why XGBoost

XGBoost is an implementation of gradient boosting on decision trees: it builds many small trees, one after another, and each new tree tries to fix the errors left by the previous ones. It works very well with tabular data, like a table of 30 numeric columns, and it doesn’t need you to normalize the variables.

SageMaker AI offers XGBoost as a built-in algorithm: AWS maintains the container, you just choose the version, pass the data in the format it expects and define the hyperparameters. You don’t write training code. For a first model, it’s the most direct way to focus on the SageMaker AI flow rather than on the library.

Preparing the data with the built-in XGBoost rules

The dataset is Breast Cancer Wisconsin (Diagnostic), which comes included in scikit-learn: 569 biopsies, 30 numeric features each and a label. There are 212 malignant cases and 357 benign. Since it comes with the library, there’s nothing to download.

Before uploading the data there are two details worth sorting out.

The label is “backwards” for what we want. In scikit-learn, 0 means malignant and 1 benign. We want the model to return the probability that a tumor is malignant, so we invert the label: 1 - target. That way, a high probability means high risk, which is how anyone would read it.

The built-in XGBoost has format rules. To train with CSV, the AWS documentation states that the label must be in the first column and that the file must not have a header. If you leave the column names, the algorithm tries to read them as numbers and training fails. If you put the label at the end, it learns to predict something else without warning you.

Three groups with three different jobs

We split the data into three parts with train_test_split, in a stratified way so each group keeps the original proportion of malignant and benign cases:

Bar with 569 patients split into train (398, 70%), validation (85, 15%) and test (86, 15%), with the role of each group.

Train teaches, validation keeps watch and test is the final exam the model has never seen.

The test group stays in the notebook and is never uploaded to S3. It’s the only honest way to measure the model at the end: with patients who took no part in any training decision.

import boto3
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sagemaker.core.helper.session_helper import Session, get_execution_role

session = Session()
region = session.boto_region_name
bucket = session.default_bucket()   # bucket SageMaker AI creates for you
role = get_execution_role()         # Studio domain execution role
prefix = "aws-sin-mapa/clasificacion-xgboost"

data = load_breast_cancer(as_frame=True)
df = data.frame
df["target"] = 1 - df["target"]                      # 1 = malignant
df = df[["target"] + list(data.feature_names)]       # label in the first column

train, temp = train_test_split(df, test_size=0.30, stratify=df["target"], random_state=42)
validation, test = train_test_split(temp, test_size=0.50, stratify=temp["target"], random_state=42)

s3 = boto3.client("s3")
for name, split in {"train": train, "validation": validation}.items():
    split.to_csv(f"{name}.csv", header=False, index=False)          # no header
    s3.upload_file(f"{name}.csv", bucket, f"{prefix}/{name}/{name}.csv")

Expected output: Filas -> train: 398 | validation: 85 | test: 86 (filas means rows).

Each group goes to its own folder in S3 (train/ and validation/) because SageMaker AI receives data through channels: each channel points to an S3 prefix and the algorithm reads every file it finds there. The channel name matters: the built-in XGBoost recognizes train and validation, and uses the second one to compute the evaluation metric on each round.

Training with ModelTrainer in SDK v3

The SageMaker Python SDK v3 reorganized the library. The Estimator, Model and Predictor classes from version 2 gave way to a unified interface: ModelTrainer (in sagemaker.train) for training, ModelBuilder (in sagemaker.serve) for deploying, and sagemaker.core for working directly with SageMaker AI resources as Python objects. If you’re coming from older tutorials, this is the change you’ll notice most.

ModelTrainer needs three things: which algorithm to use (the container image), which machine to run it on (Compute) and with which configuration (the hyperparameters).

from sagemaker.core import image_uris
from sagemaker.train import ModelTrainer
from sagemaker.train.configs import Compute, InputData, OutputDataConfig

xgb_image = image_uris.retrieve(framework="xgboost", region=region, version="1.7-1")

model_trainer = ModelTrainer(
    training_image=xgb_image,
    compute=Compute(instance_type="ml.m5.xlarge", instance_count=1),
    hyperparameters={
        "objective": "binary:logistic",
        "eval_metric": "auc",
        "num_round": 100,
        "max_depth": 4,
        "eta": 0.1,
    },
    output_data_config=OutputDataConfig(s3_output_path=f"s3://{bucket}/{prefix}/output"),
    role=role,
    base_job_name="clasificacion-xgboost",
    sagemaker_session=session,
)

model_trainer.train(
    input_data_config=[
        InputData(channel_name="train", data_source=f"s3://{bucket}/{prefix}/train/", content_type="text/csv"),
        InputData(channel_name="validation", data_source=f"s3://{bucket}/{prefix}/validation/", content_type="text/csv"),
    ],
    wait=True,
)

The container version is pinned explicitly (1.7-1). AWS recommends not using generic tags like latest, because the algorithm’s behavior could change from one run to the next.

What each hyperparameter does

Hyperparameter Value What it controls
objective binary:logistic Two-class classification. The model returns a probability between 0 and 1.
eval_metric auc The metric computed on validation on each round.
num_round 100 How many trees are built.
max_depth 4 How deep each tree can be. Shallow trees memorize less.
eta 0.1 The learning rate: how much each new tree corrects the previous ones.

They are reasonable starting values, not the optimal ones. Finding the best combination is the job of automatic hyperparameter tuning, which is left for an advanced version of the lab.

When the cell finishes without saying anything

In the test, the training cell finished without printing any log: Jupyter’s [*] indicator simply changed to a number. That doesn’t mean something failed. To be sure, the most reliable thing is to ask the SageMaker AI API for the latest training job:

sm = boto3.client("sagemaker")
job_name = sm.list_training_jobs(
    NameContains="clasificacion-xgboost", SortBy="CreationTime", SortOrder="Descending", MaxResults=1
)["TrainingJobSummaries"][0]["TrainingJobName"]

job = sm.describe_training_job(TrainingJobName=job_name)
print("Estado:", job["TrainingJobStatus"])
print("Segundos facturados:", job.get("BillableTimeInSeconds"))
for m in job.get("FinalMetricDataList", []):
    print(f"{m['MetricName']}: {m['Value']:.4f}")

The result of the test was Completed (the labels printed are status and billed seconds), with 100 billed seconds, a validation:auc of 0.9918 and a train:auc of 1.0000.

It’s worth pausing on those two numbers. AUC measures how well the model separates the two classes: 1 is a perfect separation and 0.5 is the same as flipping a coin. Being perfect on train and slightly lower on validation indicates that the model fit the examples it saw completely. With such a small dataset that’s expected and the gap is small, but it’s exactly why validation and test exist: the number that matters is never the one from the training data.

Deploying the model: the three pieces of an endpoint

To serve real-time predictions, SageMaker AI needs three resources:

  1. Model: joins the trained artifact (model.tar.gz) with the container that knows how to run it.
  2. EndpointConfig: defines which instance type to use and how many.
  3. Endpoint: turns on that infrastructure, loads the model and publishes a URL you can send requests to.

Separating the pieces makes sense in production: you can change an endpoint’s configuration (another instance, another model) without deleting it and creating it again.

Why we didn’t use ModelBuilder

In SDK v3, the high-level way to deploy is ModelBuilder. In the test, when it was given the built-in XGBoost training with ModelBuilder(model=model_trainer), it didn’t recognize the model type and failed with ValueError: Cannot detect required model or inference spec. The solution that worked was to create the three pieces directly with the sagemaker.core classes:

from sagemaker.core.resources import Model, EndpointConfig, Endpoint
from sagemaker.core.shapes import ContainerDefinition, ProductionVariant

ENDPOINT_NAME = "clasificacion-xgboost-endpoint"
model_data = job["ModelArtifacts"]["S3ModelArtifacts"]

Model.create(
    model_name=ENDPOINT_NAME,
    primary_container=ContainerDefinition(image=xgb_image, model_data_url=model_data),
    execution_role_arn=role,
)

EndpointConfig.create(
    endpoint_config_name=ENDPOINT_NAME,
    production_variants=[ProductionVariant(
        variant_name="AllTraffic",
        model_name=ENDPOINT_NAME,
        initial_instance_count=1,
        instance_type="ml.m5.large",
    )],
)

endpoint = Endpoint.create(endpoint_name=ENDPOINT_NAME, endpoint_config_name=ENDPOINT_NAME)
endpoint.wait_for_status("InService")

The endpoint takes several minutes to reach InService. From that moment, the ml.m5.large instance is running and billing by the hour, whether you use it or not.

Requesting predictions and turning probabilities into decisions

For inference, the built-in XGBoost expects the same CSV format, but without the label column. We send the 86 test patients in a single request:

import numpy as np
from sklearn.metrics import accuracy_score, confusion_matrix

X_test = test.drop(columns="target")
y_test = test["target"].values

response = endpoint.invoke(
    body=X_test.to_csv(header=False, index=False).encode("utf-8"),
    content_type="text/csv",
)
raw = response.body.read().decode("utf-8")
probabilidades = np.array([float(v) for v in raw.replace("\n", ",").split(",") if v.strip()])
predicciones = (probabilidades >= 0.5).astype(int)

print("Accuracy:", round(accuracy_score(y_test, predicciones), 4))
print(confusion_matrix(y_test, predicciones))

With binary:logistic, the endpoint doesn’t answer “malignant” or “benign”: it answers a probability per patient (probabilidades). We make the decision (predicciones) by choosing a threshold. Here we use 0.5: if the probability of malignancy is 0.5 or higher, we classify it as malignant. That threshold isn’t a law of the model, it’s a business decision, and we’ll see why it matters.

Reading the confusion matrix: 97.7% doesn’t tell the whole story

The result of the test was an accuracy of 0.9767: 84 correct out of 86. It sounds excellent. The confusion matrix shows where the two errors are:

The lab’s confusion matrix: 54 benign correctly identified, 0 false alarms, 2 malignant cases that slipped through and 30 malignant detected. Accuracy 97.7%, precision 100%, recall 93.8%.

Both errors are in the worst possible cell: malignant tumors classified as benign.

The rows are reality and the columns are what the model predicted. Read that way, the matrix [[54 0] [2 30]] says three things:

  • Zero false alarms. No benign tumor was classified as malignant. The precision for the malignant class is 100%: every time the model said “malignant”, it was right.
  • Two false negatives. Of the 32 malignant tumors in the test group, the model detected 30. Its sensitivity (or recall) is 30/32, that is, 93.8%.
  • Accuracy mixes both errors as if they cost the same, and they don’t.

In a medical problem, a false alarm means more tests and a bad time. A false negative means someone with a malignant tumor goes home believing they have nothing. That’s why, in this kind of problem, sensitivity is usually prioritized, even if that means accepting some false alarms.

This is where the threshold comes back. If you lower it (for example, from 0.5 to 0.3), the model flags more borderline cases as malignant: recall usually goes up and precision goes down. There’s no need to retrain anything: the probabilities are the same, only where you draw the line changes. Choosing that point based on the cost of each kind of error is a decision no algorithm makes for you.

The lesson applies far beyond medicine: fraud detection, spam filters, security alerts. Before celebrating a high accuracy, ask yourself which errors the model makes and how much each one costs.

Costs and cleanup

The lab costs cents if you clean up at the end. There are three billable resources:

  • The training job, for the instance time used. In the test it was 100 seconds of ml.m5.xlarge. The instance shuts itself down when it finishes.
  • The endpoint, for every hour it’s InService. It doesn’t shut itself down: if you forget it, it keeps charging even if nobody sends it requests.
  • The JupyterLab space in SageMaker Studio, for every hour it’s running.

The files in S3 are a few kilobytes. For up-to-date values by Region, check the official Amazon SageMaker AI pricing page.

To delete the endpoint, its configuration and the model from the notebook:

Endpoint.get(endpoint_name=ENDPOINT_NAME).delete()
EndpointConfig.get(endpoint_config_name=ENDPOINT_NAME).delete()
Model.get(model_name=ENDPOINT_NAME).delete()

Then, in SageMaker Studio, open your JupyterLab space and click Stop space. The notebook stays saved and the space stops billing.

If you closed the notebook before cleaning up, the repository includes a script that deletes the same resources from a JupyterLab terminal or from AWS CloudShell:

python scripts/limpiar.py              # endpoint, configuration and model
python scripts/limpiar.py --borrar-s3  # also the data and artifacts in S3

Errors that came up in the test

All of these errors came up during the real test of the lab. If you hit one, you’re not doing anything strange.

What you see What it means What to do
Lots of red pip lines about AutoGluon, numpy or pandas Other tools preinstalled in Studio ask for different versions Ignore them and update only sagemaker.
AttributeError: module 'sagemaker' has no attribute '__version__' In SDK v3 that way of checking the version no longer exists Use importlib.metadata.version("sagemaker").
SyntaxError on a line that looks fine Extra characters slipped in when copying the code Delete them or copy with the copy button.
The training cell finishes without showing anything SDK v3 doesn’t always show logs in the notebook Check the status with describe_training_job.
ValueError: Cannot detect required model or inference spec ModelBuilder doesn’t recognize the built-in XGBoost Create Model, EndpointConfig and Endpoint separately.
ResourceLimitExceeded The account has no quota for that instance type Request an increase in Service Quotas.

A configuration detail that avoids the last error: on new accounts, check before you start that you have quota available for ml.m5.xlarge (training) and ml.m5.large (endpoint).

What you take away and where to go next

With this lab you went through the full cycle of a model in SageMaker AI: data in S3 in the format the algorithm requires, a managed training job with ModelTrainer, an endpoint assembled piece by piece and an evaluation that goes beyond accuracy. Probably the most useful idea isn’t technical: a model isn’t good or bad in the abstract, it’s good or bad for the errors your problem can tolerate.

From here, the natural next steps are:

  • Script mode: writing your own training code instead of using the built-in algorithm.
  • Managed Spot Training with checkpoints: training on spare Amazon EC2 capacity to reduce training cost.
  • Automatic hyperparameter tuning: letting SageMaker AI try combinations of max_depth, eta and num_round for you.
  • Choosing the threshold based on the cost of each error, with a precision-recall curve.

The full code, the notebook and the cleanup script are in the sagemaker-clasificacion-lab repository.

References

Keep learning:

If this article helped you, share it with someone who is just getting started with the cloud. See you in the next AWS Unmapped article.