InterviewTreedInterviewTreed

InterviewTreed Question Bank

Machine Learning Interview Questions and Answers

Prepare for machine learning fundamentals, algorithms, feature engineering, model training, evaluation, optimization, and practical machine learning applications.

Total Questions

100

Beginner

30

Intermediate

40

Advanced

30

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1ML Fundamentals

What is machine learning?

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q2ML Fundamentals

What are the main types of machine learning?

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q3ML Fundamentals

Classification vs regression

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q4ML Fundamentals

Explain the typical ML workflow

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q5ML Fundamentals

What are features and labels?

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q6ML Fundamentals

What is overfitting?

Overfitting occurs when a model learns noise or quirks in training data and generalizes poorly. Look for a large training/validation gap; simplify the...

Answer

Overfitting occurs when a model learns noise or quirks in training data and generalizes poorly. Look for a large training/validation gap; simplify the model, regularize, improve data quality, or collect representative data.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

A deep decision tree gets near-perfect training accuracy but much worse validation accuracy.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Overfitting occurs when a model learns noise or quirks in training data and generalizes poorly
  • Keep test data untouched until final evaluation.
Q7ML Fundamentals

What is underfitting?

Underfitting occurs when a model is too simple or insufficiently trained to capture useful patterns. Training and validation performance are both poor...

Answer

Underfitting occurs when a model is too simple or insufficiently trained to capture useful patterns. Training and validation performance are both poor; consider better features, a more expressive model, or improved optimization.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

A shallow tree misses nonlinear patterns and performs poorly on training and validation sets.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Underfitting occurs when a model is too simple or insufficiently trained to capture useful patterns
  • Keep test data untouched until final evaluation.
Q8ML Fundamentals

Explain the bias-variance trade-off

High bias reflects restrictive assumptions; high variance reflects sensitivity to the training sample. Select complexity using validation performance,...

Answer

High bias reflects restrictive assumptions; high variance reflects sensitivity to the training sample. Select complexity using validation performance, balancing both while recognizing irreducible noise.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • High bias reflects restrictive assumptions; high variance reflects sensitivity to the training sample
  • Keep test data untouched until final evaluation.
Q9ML Fundamentals

What is a baseline model?

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q10ML Fundamentals

Parametric vs non-parametric models

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fi...

Answer

Machine learning learns patterns from examples to make predictions or decisions. Define the target and success metric, create a leakage-safe split, fit preprocessing and a model on training data, tune with validation or cross-validation, and reserve the test set for final evaluation.

Syntax

X = df[feature_columns]; y = df[target_column]
model.fit(X_train, y_train)  # learn parameters
model.predict(X_new)         # predict unseen rows

Example

Predict customer churn from account tenure, usage, and plan information; churn status is the target.

Code example

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Diagram

Raw data → Define target → Split data → Train model → Validate → Test

Key Points

  • Machine learning learns patterns from examples to make predictions or decisions
  • Keep test data untouched until final evaluation.
Q11Algorithms

How does linear regression work?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

y_hat = beta_0 + beta_1*x_1 + ... + beta_p*x_p

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q12Algorithms

Linear regression assumptions

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

y_hat = beta_0 + beta_1*x_1 + ... + beta_p*x_p

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q13Algorithms

What is logistic regression?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

P(y=1|x) = 1 / (1 + exp(-(wᵀx + b)))

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter=1000, class_weight='balanced')
model.fit(X_train, y_train)
probability = model.predict_proba(X_valid)[:, 1]

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q14Algorithms

What is a decision tree?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q15Algorithms

Gini impurity vs entropy

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q16Algorithms

What is Random Forest?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

RandomForestClassifier(n_estimators=200, max_depth=None)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, max_features='sqrt', random_state=42, n_jobs=-1)
model.fit(X_train, y_train)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q17Algorithms

What is bagging?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q18Algorithms

What is boosting?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q19Algorithms

AdaBoost vs gradient boosting

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q20Algorithms

What is XGBoost?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q21Algorithms

What is an SVM?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q22Algorithms

What is k-nearest neighbors?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q23Algorithms

What is Naive Bayes?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q24Algorithms

How does k-means clustering work?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

KMeans(n_clusters=k, n_init=10, random_state=42)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.cluster import KMeans
model = KMeans(n_clusters=4, n_init=10, random_state=42)
labels = model.fit_predict(X_scaled)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q25Algorithms

What is DBSCAN?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q26Algorithms

What is PCA?

Principal Component Analysis projects centered data onto orthogonal directions ordered by explained variance. It can reduce correlated dimensions, but...

Answer

Principal Component Analysis projects centered data onto orthogonal directions ordered by explained variance. It can reduce correlated dimensions, but components may be harder to interpret and scaling often matters.

Syntax

PCA(n_components=0.95)  # retain 95% of variance

Example

Compress correlated sensor measurements into a smaller set of principal components.

Code example

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
pca = make_pipeline(StandardScaler(), PCA(n_components=0.95))
X_reduced = pca.fit_transform(X_train)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Principal Component Analysis projects centered data onto orthogonal directions ordered by explained variance
  • Keep test data untouched until final evaluation.
Q27Algorithms

What is an artificial neural network?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q28Algorithms

What is reinforcement learning?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q29Algorithms

What is regularization?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q30Algorithms

L1 vs L2 regularization

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q31Algorithms

What is a loss function?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q32Algorithms

What is gradient descent?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q33Algorithms

What is the learning rate?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q34Algorithms

What is an ensemble model?

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune ca...

Answer

Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs. Establish a baseline, tune candidates with cross-validation, and compare them using the same splits and metric.

Syntax

Classification: model.fit(X, y_class)
Regression: model.fit(X, y_numeric)
Clustering: labels = model.fit_predict(X)

Example

Compare logistic regression, a decision tree, and a tree ensemble for the same classification task.

Code example

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_valid)

Diagram

Features → Algorithm / learned parameters → Predictions → Evaluation

Key Points

  • Choose an algorithm based on target type, data size, feature representation, interpretability, latency, and error costs
  • Keep test data untouched until final evaluation.
Q35Feature Engineering

What is feature engineering?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q36Feature Engineering

How do you handle missing values?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

SimpleImputer(strategy='median')
Fit on training data; transform validation/test with the same fitted imputer.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy='median')
X_train = imputer.fit_transform(X_train)
X_valid = imputer.transform(X_valid)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q37Feature Engineering

Mean vs median imputation

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q38Feature Engineering

How do you encode categorical variables?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

OneHotEncoder(handle_unknown='ignore')
OrdinalEncoder(categories=[ordered_values])  # only for ordered categories

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(handle_unknown='ignore')
X_train_encoded = encoder.fit_transform(X_train[categorical_columns])
X_valid_encoded = encoder.transform(X_valid[categorical_columns])

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q39Feature Engineering

When should ordinal encoding be used?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

OneHotEncoder(handle_unknown='ignore')
OrdinalEncoder(categories=[ordered_values])  # only for ordered categories

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(handle_unknown='ignore')
X_train_encoded = encoder.fit_transform(X_train[categorical_columns])
X_valid_encoded = encoder.transform(X_valid[categorical_columns])

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q40Feature Engineering

What is feature scaling?

Feature scaling makes numeric magnitudes comparable. Standardization centers and divides by standard deviation; min-max scaling maps to a range. It ma...

Answer

Feature scaling makes numeric magnitudes comparable. Standardization centers and divides by standard deviation; min-max scaling maps to a range. It matters for distance- and gradient-based methods, but usually less for tree splits.

Syntax

z = (x - mean) / standard_deviation
MinMaxScaler(feature_range=(0, 1))

Example

Scale income and account age before using KNN or an RBF-kernel SVM.

Code example

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_valid_scaled = scaler.transform(X_valid)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature scaling makes numeric magnitudes comparable
  • Keep test data untouched until final evaluation.
Q41Feature Engineering

Standardization vs normalization

Feature scaling makes numeric magnitudes comparable. Standardization centers and divides by standard deviation; min-max scaling maps to a range. It ma...

Answer

Feature scaling makes numeric magnitudes comparable. Standardization centers and divides by standard deviation; min-max scaling maps to a range. It matters for distance- and gradient-based methods, but usually less for tree splits.

Syntax

z = (x - mean) / standard_deviation
MinMaxScaler(feature_range=(0, 1))

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_valid_scaled = scaler.transform(X_valid)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature scaling makes numeric magnitudes comparable
  • Keep test data untouched until final evaluation.
Q42Feature Engineering

How do you detect outliers?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q43Feature Engineering

What is data leakage?

Data leakage occurs when training or model selection uses information unavailable at prediction time, including future data or transforms fit on valid...

Answer

Data leakage occurs when training or model selection uses information unavailable at prediction time, including future data or transforms fit on validation/test rows. Split first and fit learned preprocessing inside the training pipeline.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

A feature containing a refund issued after the prediction date leaks future information.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Data leakage occurs when training or model selection uses information unavailable at prediction time, including future data or transforms fit on validation/test rows
  • Keep test data untouched until final evaluation.
Q44Feature Engineering

What is target leakage?

Target leakage occurs when a feature directly or indirectly reveals the label, often because it is recorded after the outcome. Audit feature timestamp...

Answer

Target leakage occurs when a feature directly or indirectly reveals the label, often because it is recorded after the outcome. Audit feature timestamps and keep only information available at prediction time.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

A post-cancellation status field cannot predict cancellation before it occurs.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Target leakage occurs when a feature directly or indirectly reveals the label, often because it is recorded after the outcome
  • Keep test data untouched until final evaluation.
Q45Feature Engineering

What is feature selection?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q46Feature Engineering

Filter vs wrapper vs embedded selection

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q47Feature Engineering

What is multicollinearity?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q48Feature Engineering

What is a feature interaction?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q49Feature Engineering

How can dates be engineered into features?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q50Feature Engineering

What is the dummy-variable trap?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

OneHotEncoder(handle_unknown='ignore')
OrdinalEncoder(categories=[ordered_values])  # only for ordered categories

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(handle_unknown='ignore')
X_train_encoded = encoder.fit_transform(X_train[categorical_columns])
X_valid_encoded = encoder.transform(X_valid[categorical_columns])

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q51Feature Engineering

How do you process text for classical ML?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q52Feature Engineering

What is a preprocessing pipeline?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q53Feature Engineering

What is ColumnTransformer?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q54Feature Engineering

What is target encoding?

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when need...

Answer

Feature engineering converts raw fields into useful, prediction-time-available representations. Handle missingness, encode categories, scale when needed, derive domain features, and fit every learned transformation only on training folds to prevent leakage.

Syntax

Pipeline([('transform', transformer), ('model', estimator)])
Fit transforms on training folds; apply fitted transforms to validation/test data.

Example

Impute missing income, one-hot encode subscription plan, and derive account age from signup date.

Code example

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([('imputer', SimpleImputer(strategy='median')), ('scale', StandardScaler()), ('model', LogisticRegression(max_iter=1000))])
pipeline.fit(X_train, y_train)

Diagram

Raw columns → Impute / encode / scale / derive → Model-ready features

Key Points

  • Feature engineering converts raw fields into useful, prediction-time-available representations
  • Keep test data untouched until final evaluation.
Q55Model Selection

Why split train, validation, and test data?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q56Model Selection

What is cross-validation?

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratifi...

Answer

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratified, group-aware, or time-aware splitters as appropriate.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split
  • Keep test data untouched until final evaluation.
Q57Model Selection

K-fold vs stratified K-fold

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q58Model Selection

What is group cross-validation?

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratifi...

Answer

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratified, group-aware, or time-aware splitters as appropriate.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split
  • Keep test data untouched until final evaluation.
Q59Model Selection

When should time-series validation be used?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q60Model Selection

What is hyperparameter tuning?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q62Model Selection

What is nested cross-validation?

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratifi...

Answer

Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split. Use stratified, group-aware, or time-aware splitters as appropriate.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Cross-validation repeatedly fits on training folds and evaluates on held-out folds, providing a more stable estimate than a single split
  • Keep test data untouched until final evaluation.
Q63Model Selection

How do you choose a model-selection metric?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q64Model Selection

What is learning-curve analysis?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q65Model Selection

What is a validation curve?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q66Model Selection

What is early stopping?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q67Model Selection

How do you compare two models fairly?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q68Model Selection

How do you make experiments reproducible?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q69Model Selection

What is a model benchmark?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.
Q70Model Selection

How do you choose a production model?

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeate...

Answer

Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation. Keep the final test set out of repeated decisions; use group- or time-aware splits when observations are dependent.

Syntax

cross_val_score(estimator, X, y, cv=5, scoring='roc_auc')
GridSearchCV(estimator, param_grid, cv=5, scoring='roc_auc')

Example

Compare candidate classifiers on the same stratified folds and choose based on validation ROC-AUC and business constraints.

Code example

from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(scores.mean(), scores.std())

Diagram

Candidate models → Validation folds → Compare metric + variance → Select model

Key Points

  • Model selection estimates generalization and chooses hyperparameters using validation data or cross-validation
  • Keep test data untouched until final evaluation.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q71Evaluation & Production

What is accuracy?

Accuracy is the fraction of predictions that are correct: (TP+TN)/(TP+TN+FP+FN). It can be misleading with class imbalance or asymmetric error costs.

Answer

Accuracy is the fraction of predictions that are correct: (TP+TN)/(TP+TN+FP+FN). It can be misleading with class imbalance or asymmetric error costs.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

On a 99%-legitimate dataset, predicting every row as legitimate achieves 99% accuracy while detecting no fraud.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Accuracy is the fraction of predictions that are correct: (TP+TN)/(TP+TN+FP+FN)
  • Keep test data untouched until final evaluation.
Q72Evaluation & Production

What are precision and recall?

Precision = TP/(TP+FP), the share of predicted positives that are correct. Recall = TP/(TP+FN), the share of actual positives found. Choose the trade-...

Answer

Precision = TP/(TP+FP), the share of predicted positives that are correct. Recall = TP/(TP+FN), the share of actual positives found. Choose the trade-off based on false-alarm and missed-case costs.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

Precision matters when each alert is costly; recall matters when missing a positive case is costly.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Precision = TP/(TP+FP), the share of predicted positives that are correct
  • Keep test data untouched until final evaluation.
Q73Evaluation & Production

What is the F1 score?

F1 is the harmonic mean of precision and recall: 2PR/(P+R). It balances these measures but ignores true negatives and does not encode business costs d...

Answer

F1 is the harmonic mean of precision and recall: 2PR/(P+R). It balances these measures but ignores true negatives and does not encode business costs directly.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

Compare two fraud models when both false alarms and missed fraud cases matter.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • F1 is the harmonic mean of precision and recall: 2PR/(P+R)
  • Keep test data untouched until final evaluation.
Q74Evaluation & Production

What is a confusion matrix?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

confusion_matrix(y_true, y_pred, labels=[0, 1])

Example

Inspect false negatives for a screening system and false positives for a costly review queue.

Code example

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_valid, model.predict(X_valid), labels=[0, 1])
print(cm)

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q75Evaluation & Production

What is ROC-AUC?

ROC-AUC measures ranking quality across thresholds using true-positive rate versus false-positive rate. It is threshold-independent but can look optim...

Answer

ROC-AUC measures ranking quality across thresholds using true-positive rate versus false-positive rate. It is threshold-independent but can look optimistic with rare positives; consider PR-AUC too.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • ROC-AUC measures ranking quality across thresholds using true-positive rate versus false-positive rate
  • Keep test data untouched until final evaluation.
Q76Evaluation & Production

What is PR-AUC?

The precision-recall curve shows precision versus recall across thresholds. Average precision or PR-AUC is often informative for rare positive classes...

Answer

The precision-recall curve shows precision versus recall across thresholds. Average precision or PR-AUC is often informative for rare positive classes; its baseline depends on positive prevalence.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • The precision-recall curve shows precision versus recall across thresholds
  • Keep test data untouched until final evaluation.
Q77Evaluation & Production

What is log loss?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q78Evaluation & Production

What is model calibration?

A model is calibrated when predictions around probability p correspond to an observed event rate near p. Calibration differs from ranking quality and ...

Answer

A model is calibrated when predictions around probability p correspond to an observed event rate near p. Calibration differs from ranking quality and matters when probabilities drive risk or resource decisions.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • A model is calibrated when predictions around probability p correspond to an observed event rate near p
  • Keep test data untouched until final evaluation.
Q79Evaluation & Production

What is the Brier score?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q80Evaluation & Production

How do you choose a classification threshold?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

predict positive when predicted_probability >= chosen_threshold

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import precision_recall_curve
prob = model.predict_proba(X_valid)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_valid, prob)
# Select threshold using validation data and business costs

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q81Evaluation & Production

How do you evaluate regression models?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

MAE = mean(abs(y - y_hat))
RMSE = sqrt(mean((y - y_hat)**2))

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
pred = model.predict(X_valid)
print(mean_absolute_error(y_valid, pred))
print(mean_squared_error(y_valid, pred) ** 0.5)
print(r2_score(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q82Evaluation & Production

MAE vs MSE vs RMSE

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

MAE = mean(abs(y - y_hat))
RMSE = sqrt(mean((y - y_hat)**2))

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
pred = model.predict(X_valid)
print(mean_absolute_error(y_valid, pred))
print(mean_squared_error(y_valid, pred) ** 0.5)
print(r2_score(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q83Evaluation & Production

What is R-squared?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

MAE = mean(abs(y - y_hat))
RMSE = sqrt(mean((y - y_hat)**2))

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
pred = model.predict(X_valid)
print(mean_absolute_error(y_valid, pred))
print(mean_squared_error(y_valid, pred) ** 0.5)
print(r2_score(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q84Evaluation & Production

What is adjusted R-squared?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

MAE = mean(abs(y - y_hat))
RMSE = sqrt(mean((y - y_hat)**2))

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
pred = model.predict(X_valid)
print(mean_absolute_error(y_valid, pred))
print(mean_squared_error(y_valid, pred) ** 0.5)
print(r2_score(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q85Evaluation & Production

How do you evaluate imbalanced classification?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q86Evaluation & Production

What is class weighting?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

Resample only within training folds; keep validation/test distributions untouched.

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight='balanced', max_iter=1000)
model.fit(X_train, y_train)

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q87Evaluation & Production

Oversampling vs undersampling

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

Resample only within training folds; keep validation/test distributions untouched.

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight='balanced', max_iter=1000)
model.fit(X_train, y_train)

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q88Evaluation & Production

What is SMOTE?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

Resample only within training folds; keep validation/test distributions untouched.

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight='balanced', max_iter=1000)
model.fit(X_train, y_train)

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q89Evaluation & Production

What is permutation feature importance?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

permutation_importance(estimator, X_valid, y_valid, scoring='roc_auc')

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.inspection import permutation_importance
result = permutation_importance(model, X_valid, y_valid, n_repeats=10, random_state=42)
print(result.importances_mean)

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q90Evaluation & Production

What are limitations of impurity-based importance?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q91Evaluation & Production

What is SHAP?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q92Evaluation & Production

What is partial dependence?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q93Evaluation & Production

What is bootstrapping?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q94Evaluation & Production

What is concept drift?

Concept drift means the relationship between inputs and outcomes changes over time. Monitor performance as labels arrive, investigate changes in produ...

Answer

Concept drift means the relationship between inputs and outcomes changes over time. Monitor performance as labels arrive, investigate changes in products or populations, and retrain only after validating the cause and remedy.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Concept drift means the relationship between inputs and outcomes changes over time
  • Keep test data untouched until final evaluation.
Q95Evaluation & Production

What is covariate shift?

Covariate shift means the input distribution changes between training and deployment while the conditional target relationship is assumed stable. Comp...

Answer

Covariate shift means the input distribution changes between training and deployment while the conditional target relationship is assumed stable. Compare feature distributions and check whether production inputs fall outside training support.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Covariate shift means the input distribution changes between training and deployment while the conditional target relationship is assumed stable
  • Keep test data untouched until final evaluation.
Q96Evaluation & Production

How do you monitor a deployed model?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q97Evaluation & Production

Batch vs online inference

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q98Evaluation & Production

What is a model card?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q99Evaluation & Production

How do you evaluate fairness?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.
Q100Evaluation & Production

How do you debug poor model performance?

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after de...

Answer

Evaluate with metrics that match the business objective and error costs. Inspect class- or segment-level errors, calibration, and robustness; after deployment, monitor input quality, drift, latency, and delayed outcome metrics.

Syntax

precision = TP / (TP + FP)
recall = TP / (TP + FN)
F1 = 2 * precision * recall / (precision + recall)

Example

For rare fraud, report precision, recall, PR-AUC, and false-negative counts rather than accuracy alone.

Code example

from sklearn.metrics import classification_report, confusion_matrix
pred = model.predict(X_valid)
print(classification_report(y_valid, pred, zero_division=0))
print(confusion_matrix(y_valid, pred))

Diagram

Predictions + outcomes → Metrics / error analysis → Deploy → Monitor → Improve

Key Points

  • Evaluate with metrics that match the business objective and error costs
  • Keep test data untouched until final evaluation.

Share this question bank

Send this page to someone preparing for an interview.