Skip to content

Skill 2.2.1: Apply Amazon SageMaker AI built-in algorithms and common ML libraries


Question 1 - Selecting a Built-in Algorithm for Tabular Classification

A financial services company needs to build a fraud detection model for credit card transactions. The dataset consists of 2 million labeled tabular records with mixed feature types (numerical amounts, categorical merchant codes, timestamps). The team has limited ML expertise and wants an AWS-managed solution that handles tabular classification natively without writing custom training code. The solution must support training on GPU instances for speed and provide probability outputs for downstream risk scoring.

Which SageMaker AI built-in algorithm should the data science team use?

A) Amazon SageMaker AI Linear Learner with predictor_type='binary_classifier' B) Amazon SageMaker AI XGBoost with objective='binary:logistic' C) Amazon SageMaker AI K-Means with k=2 D) Amazon SageMaker AI Object Detection E) Amazon SageMaker AI K-Nearest Neighbors (KNN)

Click to reveal Answer & Explanation

Correct Answer: B

Correct Answer Analysis

  • B is Correct: SageMaker XGBoost is purpose-built for structured tabular classification/regression tasks. It natively handles mixed data types (numerical, categorical via one-hot encoding or built-in splits), supports GPU training via instance_type='ml.g4dn.xlarge' or ml.p3.2xlarge, outputs calibrated probabilities with binary:logistic, and scales to millions of records.

Distractor Analysis

  • A is Incorrect: While SageMaker Linear Learner can perform binary classification and output probabilities, it is a linear model (logistic regression). For fraud data with complex non-linear interactions (e.g., merchant type × transaction amount × time-of-day), a linear decision boundary likely underperforms XGBoost. Linear Learner also does not support GPU training—it is CPU-optimized.
  • C is Incorrect: K-Means is an unsupervised clustering algorithm, not a supervised classification model. It cannot learn fraud labels and outputs cluster assignments rather than fraud probabilities.
  • D is Incorrect: Object Detection is a computer vision algorithm for identifying bounding boxes around objects in images, not tabular fraud detection.
  • E is Incorrect: K-Nearest Neighbors is a lazy learning classifier that requires the entire training dataset at inference time, which is memory-intensive and slow for 2 million records, especially when low-latency fraud scoring is required. It also doesn't support GPU acceleration and requires careful feature scaling.

Best Practice: Use XGBoost for tabular classification when you need high accuracy on structured data with mixed feature types, and Linear Learner only for simple linear baselines.


Question 2 - Script Mode vs. Built-in Algorithm Trade-offs

A retail analytics company is building a demand forecasting model. Their data science team has developed a custom time-series model using PyTorch with a novel attention mechanism. The model cannot be expressed using any SageMaker built-in algorithm. The team must run this as a managed training job with zero Docker container maintenance.

Which approach should they use? (Select ONE)

A) Use the SageMaker PyTorch framework estimator with entry_point='train.py' (Script Mode) B) Package the custom PyTorch model as a Docker image and push it to Amazon ECR C) Rewrite the model using SageMaker DeepAR D) Use SageMaker Autopilot to create the model from raw data E) Train locally on an EC2 instance and manually upload the model artifacts to S3

Click to reveal Answer & Explanation

Correct Answer: A

Correct Answer Analysis

  • A is Correct: SageMaker Script Mode with framework estimators (e.g., PyTorch, TensorFlow, HuggingFace) allows the team to supply custom training code via entry_point while SageMaker manages the deep learning container, instance provisioning, model artifact upload, and logs. This meets the "zero Docker container maintenance" requirement because the framework Deep Learning Container (DLC) is maintained by AWS.

Distractor Analysis

  • B is Incorrect: BYOC (Bring Your Own Container) provides full control but requires building, testing, versioning, and patching Docker images in Amazon ECR—directly violating the zero-container-maintenance requirement.
  • C is Incorrect: Rewriting the custom attention model in DeepAR would mean discarding the team's novel architecture. DeepAR is designed for probabilistic time-series forecasting, not custom neural attention models. This would waste the team's development effort.
  • D is Incorrect: SageMaker Autopilot (AutoML) is designed to automatically generate model pipelines, not to run custom PyTorch code. It cannot reproduce the team's novel attention architecture.
  • E is Incorrect: Training locally on EC2 requires manual provisioning, scaling, checkpointing, environment setup, and artifact management—introducing substantial operational overhead compared to a managed SageMaker Script Mode job.

Best Practice: Script Mode is the ideal middle-ground—you own the training loop, AWS maintains the container.


Question 3 - Configuring a SageMaker Training Job

A machine learning engineer is configuring a SageMaker training job for a custom TensorFlow model. The training data (50 GB of images) is stored in an S3 bucket within the same region. The training script must read data using S3 access through the TensorFlow data pipeline, and the team wants the job to automatically stop if training proves unstable (loss becomes NaN).

Which combination of configurations should they set? (Select TWO)

A) Set the role parameter on the TensorFlow estimator to an IAM role with s3:GetObject permission on the training bucket B) Configure a CloudWatch alarm on TrainLoss metric that triggers a Lambda function which calls StopTrainingJob C) Set stop_condition on the training job definition with MaxRuntimeInSeconds as a safety timeout D) Use SageMaker Debugger with LossNotDecreasing rule targeting NaN tensor values E) Store the training data in memory by launching an instance with 64 GB RAM to avoid S3 read delays

Click to reveal Answer & Explanation

Correct Answers: A and C

Correct Options Analysis

  • A is Correct: The SageMaker training job assumes an IAM role provided in the role parameter of the estimator. This role needs s3:GetObject permissions on the data bucket so the TensorFlow data pipeline can read the training data directly from S3.
  • C is Correct: Using stop_condition with MaxRuntimeInSeconds ensures the job terminates when a specified wall-clock time is exceeded—a safety mechanism against runaway jobs, including those that may hang due to NaN losses causing non-convergence.

Distractor Analysis

  • B is Incorrect: While CloudWatch monitoring is a valid pattern, configuring alarms manually to trigger Lambda functions that stop training is unnecessarily complex. SageMaker provides built-in stop_condition and Debugger rules that achieve this with less operational overhead.
  • D is Incorrect: SageMaker Debugger monitors tensors for instability, but it does not provide a "LossNotDecreasing" rule. The actual rule for loss issues is LossNotDecreasing or Overfitting, and NaN detection typically requires custom Debugger rules. This option misstates Debugger's capabilities.
  • E is Incorrect: Increasing instance memory does not "replicate" S3 data into memory automatically, and 50 GB of image data typically exceeds the memory capacity of most managed training instances. The TensorFlow data pipeline handles streaming from S3 natively without manual preloading.

Best Practice: Always set a MaxRuntimeInSeconds stop condition on long-running training jobs to avoid unexpected costs from hung or unstable runs.


Question 4 - Selecting a Built-in Algorithm for Topic Modeling

A digital media company stores 500,000 customer support documents in S3. The team needs to automatically group documents into topics without manual labeling and wants minimal feature engineering effort. The solution must scale to the full corpus and provide a topic probability distribution for each document.

Which SageMaker AI built-in algorithm should they use?

A) Amazon SageMaker AI K-Means with TF-IDF features B) Amazon SageMaker AI Latent Dirichlet Allocation (LDA) C) Amazon SageMaker AI Random Cut Forest (RCF) D) Amazon SageMaker AI Sequence-to-Sequence (Seq2Seq) E) Amazon SageMaker AI Object2Vec

Click to reveal Answer & Explanation

Correct Answer: B

Correct Answer Analysis

  • B is Correct: SageMaker Latent Dirichlet Allocation (LDA) is an unsupervised topic modeling algorithm that operates directly on text corpora. It learns a set of latent topics and outputs a probability distribution over topics for each document. It handles large-scale text datasets natively without needing manual labels and is designed for exactly this kind of document clustering/classification use case.

Distractor Analysis

  • A is Incorrect: K-Means clustering operates on feature vectors and requires manual TF-IDF feature extraction (via a script). While K-Means could cluster documents, LDA is the more natural fit for probabilistic topic modeling because it directly models words as mixture distributions—avoiding the manual feature engineering that K-Means imposes.
  • C is Incorrect: Random Cut Forest is designed for anomaly detection in multivariate time-series data, not document clustering.
  • D is Incorrect: Sequence-to-Sequence is a supervised algorithm used for machine translation, summarization, and other sequence transformation tasks. It requires labeled input-output pairs and is not designed for unsupervised topic grouping.
  • E is Incorrect: Object2Vec is a general-purpose embedding algorithm for arbitrary objects (including text). While it can produce document embeddings (which could be clustered externally), it does not output topic probability distributions and requires additional clustering steps.

Best Practice: Use LDA when your goal is interpretable probabilistic topic distributions from a document corpus without manual labeling.


Question 5 - Built-in Algorithm for Anomaly Detection

A manufacturing company monitors IoT sensor data from 10,000 factory machines at 60-second intervals. Each data point includes 20 numeric features (temperature, pressure, vibration, etc.). The team needs to detect irregular patterns in individual machines and flag them for maintenance. The model must be trained online as new sensor data arrives and must scale to high-throughput streaming data.

Which SageMaker AI built-in algorithm meets this requirement?

A) Amazon SageMaker AI Linear Learner with predictor_type='regressor' B) Amazon SageMaker AI Object2Vec with sensor embeddings C) Amazon SageMaker AI Random Cut Forest (RCF) D) Amazon SageMaker AI K-Means with cluster distance thresholds E) Amazon SageMaker AI XGBoost with objective='reg:logistic'

Click to reveal Answer & Explanation

Correct Answer: C

Correct Answer Analysis

  • C is Correct: SageMaker Random Cut Forest (RCF) is a built-in unsupervised anomaly detection algorithm designed for multivariate data streams. It works by building an ensemble of random cut trees and assigning anomaly scores based on the complexity of isolating each point. RCF is optimized for streaming use cases and provides both batch training and real-time inference (via a SageMaker endpoint). It scales to high-throughput IoT sensor data like the one described.

Distractor Analysis

  • A is Incorrect: Linear Learner with predictor_type='regressor' performs regression, not anomaly detection. It requires labeled training data (target values) and does not natively output anomaly scores.
  • B is Incorrect: Object2Vec learns embeddings for arbitrary objects through supervised or unsupervised objectives, but it does not directly output anomaly scores. It would require additional downstream processing (e.g., outlier detection on embeddings).
  • D is Incorrect: K-Means with distance thresholds can be used for anomaly detection (points far from cluster centers), but SageMaker K-Means does not natively provide streaming anomaly scores and requires setting distance thresholds manually. RCF provides a more direct and robust mechanism for streaming anomaly scoring.
  • E is Incorrect: XGBoost with objective='reg:logistic' is a regression or classification algorithm that requires labeled ground truth (e.g., "failure" vs. "normal"). For unlabeled IoT anomaly detection, supervised learning is not appropriate unless labeled failure events are available.

Best Practice: Random Cut Forest is SageMaker's built-in solution for unsupervised anomaly detection on streaming multivariate data, especially for IoT and operational use cases.


Question 6 - Built-in Algorithm for Text Classification

A customer service startup wants to classify incoming support tickets into 15 predefined categories (e.g., "Billing", "Technical", "Account", "Returns"). The team has 80,000 labeled customer support records with text fields (subject, body). They need a SageMaker built-in algorithm that handles text classification without them having to build a custom NLP pipeline.

Which algorithm should they use?

A) Amazon SageMaker AI BlazingText with supervised mode (Text Classification) B) Amazon SageMaker AI Semantic Segmentation C) Amazon SageMaker AI IP Insights D) Amazon SageMaker AI Factorization Machines E) Amazon SageMaker AI Image Classification

Click to reveal Answer & Explanation

Correct Answer: A

Correct Answer Analysis

  • A is Correct: SageMaker BlazingText is a built-in algorithm for word2vec-style embeddings and text classification. In supervised mode (mode='supervised'), it performs text classification using fastText-like techniques—learning n-gram representations and classifying text into labeled categories (e.g., 15 ticket types). It is optimized for large text corpora and multiclass classification, requiring no custom NLP feature engineering.

Distractor Analysis

  • B is Incorrect: Semantic Segmentation is a computer vision algorithm for pixel-level image segmentation (e.g., identifying roads vs. cars). It is unrelated to text data.
  • C is Incorrect: IP Insights identifies patterns in IP addresses for security monitoring and user authentication anomalies. It is not designed for text classification.
  • D is Incorrect: Factorization Machines is a sparse-matrix factorization algorithm for recommendation systems and click prediction. It requires user-item interaction matrices, not raw text.
  • E is Incorrect: Image Classification is a computer vision algorithm for categorizing image content, not text.

Best Practice: BlazingText is SageMaker's native built-in algorithm for text classification (supervised mode) and word embeddings (unsupervised mode).


Question 7 - Managed Training with SageMaker Estimator Configuration

A machine learning engineer is setting up a SageMaker PyTorch training job using the PyTorch framework estimator. The training data is stored in S3 as .npy files (NumPy arrays) and needs to be passed to the training script. The team wants to configure the number of epochs (3 epochs) and batch size (32) from the training job configuration, not hardcoded in the script.

Which code snippet correctly passes these parameters to the training job?

A)

from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_type='ml.p3.2xlarge',
    instance_count=1,
    framework_version='2.1',
    py_version='py310',
    hyperparameters={
        'epochs': 3,
        'batch-size': 32
    }
)
estimator.fit({'training': 's3://bucket/train/'})

B)

from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_type='ml.p3.2xlarge',
    instance_count=1,
    framework_version='2.1',
    py_version='py310',
    epochs=3,
    batch_size=32
)
estimator.fit('s3://bucket/train/')

C)

from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_type='ml.p3.2xlarge',
    instance_count=1,
    framework_version='2.1',
    py_version='py310',
    metrics_definition=[{'Name': 'train:loss', 'Regex': 'loss: ([0-9\\.]+)'}]
)
estimator.fit({'epochs': 3, 'batch_size': 32})

D)

from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_type='ml.p3.2xlarge',
    instance_count=1,
    framework_version='2.1',
    py_version='py310',
    environment={
        'EPOCHS': '3',
        'BATCH_SIZE': '32'
    }
)
estimator.fit({'training': 's3://bucket/train/'})

E)

from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_type='ml.p3.2xlarge',
    instance_count=1,
    framework_version='2.1',
    py_version='py310',
    hyperparameters={
        'epochs': '3',
        'batch-size': '32'
    }
)
estimator.fit({'training': 's3://bucket/train/'})

Click to reveal Answer & Explanation

Correct Answers: A and E

Correct Options Analysis

  • A is Correct: Passing hyperparameters via the hyperparameters dict with integer values is valid. SageMaker passes them as command-line arguments to the training script (e.g., --epochs 3 --batch-size 32). The fit() method also correctly specifies the S3 input channel as a dict.
  • E is Correct: Passing hyperparameters as strings is also valid (e.g., 'epochs': '3'). When SageMaker passes these to the training script, the script can parse them as strings or use argparse with type casting. Both int and str values are accepted and converted to command-line args.

Distractor Analysis

  • B is Incorrect: The SageMaker PyTorch estimator does not accept arbitrary top-level parameters like epochs and batch_size. These must be specified in the hyperparameters dict. Also, the fit() should use a channel name ({'training': ...} when using a single input channel).
  • C is Incorrect: metrics_definition configures CloudWatch metric parsing from training log output, not hyperparameters. The fit() method expects S3 data paths, not hyperparameter dictionaries.
  • D is Incorrect: The environment parameter sets environment variables for the container (accessible via os.environ in the script), but SageMaker hyperparameters passed via the hyperparameters dict are the standard pattern and appear as command-line args. Using environment for training hyperparameters is not the intended pattern and the script would need to explicitly read them from environment variables rather than argparse.

Best Practice: Use the hyperparameters dict in the SageMaker estimator to pass training hyperparameters; these are injected as command-line arguments via argparse in your script.


Question 8 - Integrating SageMaker Built-in Algorithm with DLC Framework

A biotechnology company is training a TensorFlow model for protein-structure prediction. The training script (train.py) uses custom layers, custom loss functions, and a complex data augmentation pipeline in TensorFlow 2.x. The team wants SageMaker to run this job using the latest TensorFlow version in AWS Deep Learning Containers, and they also want to specify the number of steps per epoch.

Which two parameters should they configure on the TensorFlow estimator? (Select TWO)

A) framework_version='2.13' to pick the TensorFlow version B) entry_point='train.py' to provide the custom training script C) algorithm='tensorflow' to select the TensorFlow built-in algorithm D) train_step_per_epoch=100 to configure steps per epoch E) hyperparameters={'steps-per-epoch': 100} to configure steps per epoch

Click to reveal Answer & Explanation

Correct Answers: A and B

Correct Options Analysis

  • A is Correct: Setting framework_version='2.13' specifies which TensorFlow version to use from SageMaker's Deep Learning Container catalog. This ensures consistency across runs and aligns with the team's development environment.
  • B is Correct: Providing entry_point='train.py' tells SageMaker to inject the custom training script into the TensorFlow container. This is the core of Script Mode—the logic is theirs, the container is managed.

Distractor Analysis

  • C is Incorrect: There is no algorithm parameter on the SageMaker TensorFlow estimator. Framework estimators (TensorFlow, PyTorch, etc.) are distinct from built-in algorithms (XGBoost, Linear Learner). To use a built-in TensorFlow algorithm (e.g., SageMaker's TensorFlow-based algorithms), you'd use a different estimator or interface.
  • D is Incorrect: train_step_per_epoch is not a valid parameter on the SageMaker estimator. The correct way to pass this would be as a hyperparameter (e.g., via hyperparameters={'steps-per-epoch': 100}).
  • E is Incorrect: While this option uses hyperparameters correctly, the question likely expects train_step_per_epoch not steps-per-epoch, and only one of D or E could be correct—the question asks for two valid configurations (A and B). The specific steps-per-epoch value is a custom hyperparameter consumed inside the training script; it is not a SageMaker framework parameter.

Best Practice: The framework_version and entry_point parameters on framework estimators control which container version runs and what code executes.


Question 9 - Feature Engineering with SageMaker Built-in Algorithms

An e-commerce platform needs to build a click-through rate (CTR) prediction model. The dataset consists of 100 million click records with user IDs, item IDs, and contextual features (time, device, category). User and item IDs are high-cardinality categorical variables (millions of unique values each). The team needs a SageMaker built-in algorithm that natively handles sparse high-dimensional data and supports classification (click vs. no-click).

Which algorithm should they use?

A) Amazon SageMaker AI K-Means B) Amazon SageMaker AI Factorization Machines with predictor_type='binary_classifier' C) Amazon SageMaker AI Principal Component Analysis (PCA) D) Amazon SageMaker AI Latent Dirichlet Allocation (LDA) E) Amazon SageMaker AI Sequence-to-Sequence

Click to reveal Answer & Explanation

Correct Answer: B

Correct Answer Analysis

  • B is Correct: SageMaker Factorization Machines (FM) is designed for high-dimensional sparse data like recommendation systems and CTR prediction. FM models feature interactions efficiently through factorized parameters, handles millions of unique user/item IDs natively (no one-hot encoding blow-up), and supports binary classification via predictor_type='binary_classifier'.

Distractor Analysis

  • A is Incorrect: K-Means clusters data points into groups—it does not perform classification and cannot predict click probability. It also requires numeric features (would require manual encoding of high-cardinality categorical variables).
  • C is Incorrect: PCA is a dimensionality reduction algorithm, not a predictor. It reduces feature space but cannot output click/no-click predictions.
  • D is Incorrect: LDA is for topic modeling of text documents, not tabular recommendation/CTR prediction.
  • E is Incorrect: Sequence-to-Sequence is for text generation and transformation (translation, summarization), not sparse tabular classification.

Best Practice: Factorization Machines is the SageMaker built-in algorithm of choice for sparse high-cardinality tabular data in recommendation and CTR prediction tasks.


Question 10 - Selecting the Correct SageMaker Estimator Class

A machine learning team needs to run a scikit-learn training script on SageMaker. The script performs data preprocessing (using pandas and scikit-learn transformers) and trains a random forest classifier. The dataset is 5 GB of CSV data in S3, and the team wants to avoid managing Docker containers.

Which SageMaker estimator should they use?

A) sagemaker.sklearn.SKLearn B) sagemaker.tensorflow.TensorFlow C) sagemaker.pytorch.PyTorch D) sagemaker.xgboost.XGBoost E) sagemaker.estimator.Estimator with a custom container

Click to reveal Answer & Explanation

Correct Answer: A

Correct Answer Analysis

  • A is Correct: The sagemaker.sklearn.SKLearn estimator is purpose-built for scikit-learn workloads. It uses a SageMaker-managed scikit-learn Deep Learning Container and supports Script Mode (entry point). It provides the training script with S3 data access via input channels and automatically handles artifact upload.

Distractor Analysis

  • B is Incorrect: The TensorFlow estimator is designed for TensorFlow framework scripts, not scikit-learn code. While you could install scikit-learn inside the TensorFlow container via requirements.txt, this is unnecessary overhead.
  • C is Incorrect: The PyTorch estimator is for PyTorch scripts. Scikit-learn is not the native framework for this container.
  • D is Incorrect: The xgboost.XGBoost estimator is for SageMaker's XGBoost built-in algorithm, not arbitrary scikit-learn scripts.
  • E is Incorrect: Using Estimator with a custom container (BYOC) requires building, pushing, and managing Docker images in ECR—directly violating the team's requirement to avoid container management.

Best Practice: Select the estimator that matches your training framework (SKLearn, TensorFlow, PyTorch, etc.) to leverage AWS-maintained containers and Script Mode without Docker overhead.