AI and Machine Learning Background Questions
A synopsis of applied artificial intelligence and machine learning experience including models, frameworks, and pipelines used, datasets and scale, production deployment experience, evaluation metrics, and measurable business outcomes. Candidates should describe specific projects, roles played, research versus production distinctions, and technical choices and trade offs.
HardTechnical
122 practiced
A clinical triage model used in a hospital must provide per-patient explanations and be auditable by regulators. Propose an explainability framework that balances predictive accuracy and interpretability: model choice considerations, global and local explainers, concise explanation templates clinicians can understand, human validation processes with clinicians, logging and audit trails for each decision, and how you'd test explanations for clinical usefulness and safety.
Sample Answer
Requirements & trade-offs:- Must be auditable, provide per‑patient (local) explanations, and maintain high predictive performance. Balance by preferring intrinsically interpretable models for lower-risk decisions and using black‑box models with strong explainers where necessary, with extra governance.Model choice:- Tiered approach: start with interpretable models (logistic regression with monotonic constraints, GAMs, decision rules/trees) as baseline. If performance gap > acceptable threshold, use calibrated ensemble (e.g., gradient-boosted trees) but restrict complexity and apply robust explainability + uncertainty estimates.- Require model cards, data lineage, fairness metrics, and clinical risk thresholds.Global & local explainers:- Global: feature importance (SHAP summary), partial dependence / ALE plots, cohort-level counterfactual analyses to show behavior across patient subgroups.- Local: SHAP values for each prediction, counterfactual suggestions (minimal actionable changes), rule-extraction (Anchors/LIME-like) to produce human-readable decision rules for each patient.- Always present uncertainty (confidence intervals, calibration plots, and prediction intervals).Concise clinician-facing templates:- One-line summary: risk class and top 3 drivers (direction + magnitude).- Actionable note: recommended next step(s) and what would change the risk (counterfactual).- Confidence & provenance: probability with calibration band, model version, data snapshot, timestamp.Example: “Patient A: 18% 24‑hr deterioration risk. Top drivers: SpO2 low (-0.12 SHAP), RR high (+0.08), age (+0.03). Recommended: repeat SpO2, consider O2 trial. Model v2.1, P(conf)=0.18±0.05.”Human validation & governance:- Clinician-in-the-loop evaluation: run retrospective chart reviews where clinicians rate explanations on clarity, actionability, and trust (Likert + qualitative). Use simulated prospective shadow deployments to collect clinician feedback without affecting care.- Regular multidisciplinary review board (data scientists, clinicians, ethicists, compliance) to sign off model updates and thresholds.- Training sessions and quick reference guides for clinicians; escalation pathways for disagreements.Logging & audit trails:- Immutable per-decision log: patient ID (pseudonymized), timestamp, model version, input snapshot, preprocessed features, prediction, uncertainty, local explanation (SHAP vector or serialized rule), counterfactuals shown, clinician actions/overrides, and link to data provenance.- Store logs in append-only storage with retention policy, access controls, and searchable indices for regulators.- Automated alerts for shift detection (data drift, label drift) and unusual override patterns.Testing explanations for usefulness & safety:- Fidelity tests: ensure local explanations accurately reflect model (feature‑removal, permutation sensitivity tests).- Clinical utility trials: A/B or stepped‑wedge trials comparing decisions/clinical outcomes with vs without explanations; measure changes in decision concordance, time-to-decision, and patient outcomes.- Safety checks: adversarial-case testing, counterfactual plausibility (avoid impossible suggestions), worst‑case scenario simulations, and fairness audits across demographics.- Monitor post‑deployment: track calibration, override rates, downstream outcomes, and clinician feedback; trigger retraining or rollback when pre-specified safety signals occur.Why this balances accuracy & interpretability:- Interpretable models used where sufficient; when black boxes are necessary, combine rigorous local/global explainers, uncertainty quantification, human validation, and auditable logs so regulators and clinicians can trace and trust each decision. Continuous monitoring and clinician governance ensure safety and continual improvement.
MediumTechnical
64 practiced
Design a near real-time fraud/anomaly detection solution for transactions that must operate at high scale (e.g., 100k transactions per second). Discuss model choices (supervised classifier vs unsupervised density estimators vs hybrid two-stage systems), feature pipeline latency constraints, evaluation strategies for very rare events, labeling strategy and feedback loops, and pragmatic approaches to reduce false positives while maintaining recall.
Sample Answer
Requirements & constraints:- Throughput: 100k TPS, sub-100ms end-to-end decision (ideally <50ms for decisioning).- Accuracy: high recall on fraud (rare events) while minimizing false positives to avoid friction.- Ops: streaming infra (Kafka), stateless scoring for scale, model update cadence daily/weekly.Overall architecture (high-level):- Ingest transactions via Kafka → lightweight feature enrichers (lookup caches, in-memory state) → Stage 1 fast filter (low-latency model) → Stage 2 heavier scorer/contextual analysis + rules → decision + async batch recheck/alerting. Use Redis/inline RocksDB for stateful features.Model choices:- Two-stage hybrid is pragmatic. - Stage 1: ultra-fast supervised classifier (e.g., logistic regression / small tree ensemble with ONNX/Treelite) or a distilled neural model for sub-ms inference. Goal: high recall, low compute. - Stage 2: stronger models (gradient boosted trees, deep nets, graph-based models, or unsupervised density estimators / autoencoders) that run only on candidates to improve precision. - Complement with rule-based heuristics and graph analytics (suspicious device/IP linkage).Feature pipeline & latency:- Split features into: - Inline features (<5–10ms): transaction fields, cached user/device risk, recent velocity counters in Redis. - Async/enrichment (<50–200ms tolerated for Stage 2): external fraud lists, graph features computed periodically, ML features updated in streaming jobs (Flink/Spark Structured Streaming).- Ensure deterministic, versioned feature transformations; use feature-store with real-time and batch materialization.Evaluation for rare events:- Use stratified sampling, importance sampling, and simulated fraud injection to increase positive examples during validation.- Metrics beyond ROC: Precision@k, recall at fixed FPR, PR curve, cost-sensitive metrics (expected loss), calibration.- Use cross-validation over time (time-series split) and backtesting on historical windows with production-like feature freshness.Labeling & feedback loops:- Multi-source labeling: chargebacks, manual investigator labels, heuristics. Assign label certainty and latency metadata.- Build a label pipeline that timestamps labels; maintain decay and labeling windows to link labels to transactions.- Active learning: prioritize ambiguous, high-uncertainty, or high-value transactions for investigator review to get labels faster.- Continuous retraining with online learning/updating for concept drift; monitor model drift and data distribution drift.Reducing false positives while keeping recall:- Two-stage scoring: tune Stage 1 for high recall, Stage 2 for precision.- Use cost-sensitive thresholds per customer segment and dynamic thresholding based on current fraud rates.- Implement self-service friction tiers: soft block (challenge step-up like 2FA) vs hard block.- Explainable signals: provide reasons to investigators and for automated suppression (e.g., whitelists, trusted merchants).- Calibration & ensemble: combine probabilistic outputs calibrated by isotonic regression and use stacking with rules to reduce spurious flags.- A/B test threshold policies and measure business impact (fraud prevented vs customer friction).Operational & safety:- Monitoring: per-model latency, input feature drift, precision/recall, false positive rates by cohort.- Canary deploys, shadow mode to compare new models without impacting users.- Capacity: horizontally scale stateless scoring, cache hot keys, backpressure on Kafka to protect downstream.This design balances latency and detection power with pragmatic operational controls to reduce false positives while maintaining high recall.
HardSystem Design
82 practiced
Design a multi-tenant ML platform to support multiple product teams with shared services for model training, serving, and monitoring. Include feature store design, model registry, autoscaling compute, data access controls, tenant isolation (compute and data), cost allocation and quotas, API patterns for self-service, and how you'd implement auditability, reproducibility, and governance across tenants.
Sample Answer
Requirements & constraints:- Multiple product teams (tenants) need self-service model training, serving, monitoring.- Strong data isolation, RBAC, auditability, reproducibility, cost tracking, quotas.- Scale to many concurrent experiments and production models; low-latency serving for some tenants.High-level architecture:- Shared control plane (APIs, auth, registry, telemetry, scheduler) + isolated data plane per tenant (compute namespaces, storage).- Core services: Feature Store, Model Registry, Training Orchestrator (K8s + autoscaling), Serving Platform (serverless + model-server pods), Monitoring & Alerting, Billing/Quota Service, Audit Log + Lineage Store, Governance UI.Feature store design:- Hybrid: centralized metadata/catalog + tenant-scoped stores.- Online store: per-tenant Redis/Key-Value with strict RBAC; Offline store: partitioned parquet on S3 with tenant prefix and IAM policies.- Feature definitions + transformation code stored in the metadata service with versioning and lineage.Model registry:- Single control-plane registry with tenant-scoped namespaces. Stores model artifacts (S3), metadata (schema, metrics), training code hash, environment (container/Conda), lineage to data/features, and signed provenance.- Promote lifecycle states (staging → approved → production) with approvals and immutable versions.Autoscaling compute:- K8s cluster per environment with namespaces per tenant; use Karpenter/HPA for pod autoscaling and cluster autoscaler. For heavy isolation, spawn ephemeral tenant clusters (spot or Fargate) for training jobs.- Use preemptible/spot pools + managed GPU nodes; training orchestrator schedules to cheapest compliant pool respecting quotas.Data access controls & tenant isolation:- IAM + mTLS + per-tenant K8s namespaces and network policies.- Storage partitioning: S3 prefixes + bucket policies, separate DB schemas, and encryption keys per tenant (KMS).- Optional VPC isolation for high-security tenants.Cost allocation & quotas:- Tag all compute, storage, and infra resources with tenant & project tags. Central billing service ingests cloud billing + resource telemetry and attributes costs.- Implement soft+hard quotas via orchestrator (CPU/GPU hours, storage); notify when approaching limits; require approvals to raise quotas.API patterns for self-service:- REST/GraphQL control-plane APIs and CLI + SDK (python) for: register datasets/features, launch training experiments, publish models, deploy endpoints, request quota, view cost.- Templates for reproducible experiments (infrastructure as code + experiment manifests).Auditability, reproducibility, governance:- Immutable audit logs (write-once storage + append-only DB) for all control-plane actions; store cryptographic hashes for artifacts.- Lineage store links dataset versions, feature definitions, code commit hash, environment/container image, hyperparameters, and training run outputs.- Reproducibility: save full experiment snapshot (data query, feature hashes, code repo commit, container image, random seeds). Provide one-click “re-run” that recreates env and replays job.- Governance: approval workflows in registry, automated policy checks (data sensitivity scanning, PII detection) before training or deployment, periodic policy reviews, and role-based access controls with least privilege.Trade-offs:- Centralized control plane simplifies governance but is a single point to secure.- Per-tenant compute increases cost but simplifies isolation; use mixed strategy to balance.Operational metrics:- Track training latency, serving SLOs, feature freshness, cost per tenant, model performance drift; expose dashboards and alerts.This design gives data scientists a self-service, auditable, and secure multi-tenant ML platform while enabling governance and cost control.
HardTechnical
77 practiced
Implement a scikit-learn compatible Python estimator class that wraps a TensorFlow Keras classification model and supports fit(), predict(), predict_proba(), get_params(), and set_params() so it can be used in GridSearchCV. Ensure the wrapper saves and loads Keras artifacts (model weights and architecture), accepts class_weight and sample_weight in fit(), and allows setting random seeds for reproducibility. Provide well-documented code and explain how to integrate the wrapper into an sklearn Pipeline.
Sample Answer
Below is a scikit-learn compatible estimator that wraps a TensorFlow Keras classification model. It implements fit, predict, predict_proba, get_params, set_params, saves/loads Keras artifacts (architecture JSON + weights), accepts class_weight and sample_weight, and provides a seed parameter for reproducibility.Approach:- The wrapper accepts a build_fn that, given parameters, returns a compiled tf.keras.Model.- get_params/set_params expose hyperparameters for GridSearchCV.- fit saves the final model to a temp directory (architecture JSON + weights) and reloads to ensure serialization works.- predict_proba/predict use the loaded model.- seed sets Python, NumPy, and TF seeds.Code:Key points and rationale:- build_fn pattern mirrors KerasClassifier in wrappers but preserves Keras artifacts explicitly so GridSearchCV can clone/serialize.- get_params/set_params expose hyperparameters for GridSearchCV.- seed sets PYTHONHASHSEED, NumPy, and TF seeds for reproducibility.- predict/predict_proba handle binary and multiclass.Integration into an sklearn Pipeline:- You can place KerasSKClassifier as the final estimator in sklearn.pipeline.Pipeline. Preprocessing transformers (StandardScaler, PCA) will transform numpy arrays; ensure build_fn expects input shapes accordingly.Example:Notes and caveats:- Keras models are not trivially deep-copied; this wrapper saves architecture+weights to simulate persistence that works across GridSearch CV processes.- When using n_jobs>1 in GridSearchCV, ensure each process can access TF/GPU resources; consider n_jobs=1 or configure TF for CPU-only in worker processes.- For strict reproducibility across processes and machines, set seeds and control other nondeterministic ops (TF determinism flags).
python
import os
import json
import tempfile
import shutil
from pathlib import Path
import numpy as np
import tensorflow as tf
from sklearn.base import BaseEstimator, ClassifierMixin
class KerasSKClassifier(BaseEstimator, ClassifierMixin):
"""
Scikit-learn wrapper for a TensorFlow Keras classification model.
Parameters (examples):
- build_fn: callable(**params) -> compiled tf.keras.Model
- epochs: int
- batch_size: int
- verbose: int
- seed: int or None
- model_dir: str or None (if None, uses temporary dir)
- **fit_kwargs forwarded to model.fit (e.g., validation_data)
"""
def __init__(self, build_fn,
epochs=10,
batch_size=32,
verbose=0,
seed=None,
model_dir=None,
**kwargs):
self.build_fn = build_fn
self.epochs = int(epochs)
self.batch_size = int(batch_size)
self.verbose = int(verbose)
self.seed = seed
self.model_dir = model_dir
# any extra hyperparameters forwarded to build_fn
self.build_params = kwargs
# internal
self._model = None
self._model_path = None
def _set_seed(self):
if self.seed is None:
return
os.environ['PYTHONHASHSEED'] = str(self.seed)
np.random.seed(self.seed)
tf.random.set_seed(self.seed)
def _ensure_model_dir(self):
if self.model_dir:
os.makedirs(self.model_dir, exist_ok=True)
return self.model_dir
td = tempfile.mkdtemp(prefix="keras_sklearn_")
return td
def fit(self, X, y, sample_weight=None, class_weight=None, **fit_kwargs):
"""
Fit the Keras model.
Accepts sample_weight and class_weight.
"""
self._set_seed()
# build model
params = dict(self.build_params)
model = self.build_fn(**params)
if not isinstance(model, tf.keras.Model):
raise ValueError("build_fn must return a compiled tf.keras.Model")
# convert X,y to numpy
X_np = np.asarray(X)
y_np = np.asarray(y)
# fit
history = model.fit(
X_np, y_np,
epochs=self.epochs,
batch_size=self.batch_size,
verbose=self.verbose,
sample_weight=sample_weight,
class_weight=class_weight,
**fit_kwargs
)
# save model architecture + weights to allow GridSearchCV cloning/serialization
model_dir = self._ensure_model_dir()
arch_path = Path(model_dir) / "model_arch.json"
weights_path = Path(model_dir) / "model_weights.h5"
# architecture
with open(arch_path, "w") as f:
f.write(model.to_json())
# weights
model.save_weights(str(weights_path))
# keep paths and a loaded model for predictions
self._model_path = model_dir
# to ensure a fresh loaded model (simulate serialization)
loaded = tf.keras.models.model_from_json(json.load(open(arch_path)))
loaded.load_weights(str(weights_path))
# compiled state is not preserved by model_from_json; recompile using build_fn or compile args:
# if build_fn returns compiled model, prefer re-building compile config:
try:
# attempt to recompile using the original compiled optimizer/loss if available
compiled = model.optimizer.get_config(), model.loss
# best-effort: recompile loaded with same optimizer config
opt_config = model.optimizer.get_config()
opt_class = model.optimizer.__class__
loaded.compile(optimizer=opt_class.from_config(opt_config), loss=model.loss, metrics=getattr(model, 'metrics', None))
except Exception:
# fallback: skip compile; predict/predict_proba don't need compilation
pass
self._model = loaded
return self
def predict_proba(self, X):
if self._model is None:
raise ValueError("Model is not fitted yet.")
X_np = np.asarray(X)
probs = self._model.predict(X_np, batch_size=self.batch_size, verbose=self.verbose)
# ensure 2D probability output
return probs
def predict(self, X):
probs = self.predict_proba(X)
# for binary and multiclass
if probs.ndim == 1 or probs.shape[1] == 1:
# binary: threshold 0.5
return (probs.ravel() > 0.5).astype(int)
else:
return np.argmax(probs, axis=1)
def save(self, path):
"""Persist wrapper (model artifacts already saved during fit)."""
if self._model_path is None:
raise ValueError("No model artifacts to save. Fit first.")
shutil.copytree(self._model_path, path, dirs_exist_ok=True)
def load(self, path):
"""Load persisted artifacts from path."""
arch_path = Path(path) / "model_arch.json"
weights_path = Path(path) / "model_weights.h5"
if not arch_path.exists() or not weights_path.exists():
raise ValueError("Missing model artifacts in path.")
model = tf.keras.models.model_from_json(json.load(open(arch_path)))
model.load_weights(str(weights_path))
self._model = model
self._model_path = path
return self
# scikit-learn compatibility
def get_params(self, deep=True):
# include build_fn and build_params
params = {
"build_fn": self.build_fn,
"epochs": self.epochs,
"batch_size": self.batch_size,
"verbose": self.verbose,
"seed": self.seed,
"model_dir": self.model_dir,
}
params.update(self.build_params)
return params
def set_params(self, **params):
# set known hyperparameters; unknown pass into build_params
for key, val in params.items():
if hasattr(self, key):
setattr(self, key, val)
else:
self.build_params[key] = val
return selfpython
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("scaler", StandardScaler()),
("keras", KerasSKClassifier(build_fn=build_fn, epochs=20, batch_size=64, seed=42))
])
from sklearn.model_selection import GridSearchCV
param_grid = {"keras__epochs": [10,20], "keras__learning_rate": [1e-3, 1e-4]}
gs = GridSearchCV(pipe, param_grid, cv=3)
gs.fit(X_train, y_train)MediumTechnical
90 practiced
As the owner of several production models, design a monitoring plan that captures model performance degradation, data and concept drift, input feature integrity, latency and throughput SLOs, and business KPI impact. Include specific metrics (e.g., PSI, KL divergence, rolling accuracy, latency percentiles), thresholding/alerting rules, visualization dashboard recommendations, and an on-call playbook for alert triage and remediation.
Sample Answer
Monitoring plan overview: detect model degradation, data & concept drift, feature integrity, SLOs (latency/throughput), and business KPI impact with automated alerts, dashboards, and an on-call playbook.Metrics & detection- Model performance: rolling accuracy/ROC-AUC/F1 on labeled data (7-, 30-day windows). Alert if 7-day rolling metric drops >5% absolute OR >15% relative vs baseline.- Data drift: Population Stability Index (PSI) per numeric feature (daily); KL divergence for categorical distributions. Alert if PSI>0.2 (moderate) or >0.3 (severe) OR KL > 0.5.- Concept drift: Label-conditioned drift — compare predicted vs actual conditional distributions; feature importance shift (SHAP mean abs change). Alert when performance drop aligns with significant concept measures.- Feature integrity: null rate, cardinality, out-of-range counts per feature. Alert if null rate increases >3x baseline or new category >1% of traffic.- Latency & throughput SLOs: p50/p95/p99 latencies; throughput (requests/sec). SLO: p95 latency < 200ms, p99 < 500ms, throughput >= expected. Alert on p95 breach or sustained p99 > threshold for 5 minutes.- Business KPIs: conversion rate, revenue per user, churn — monitor daily/weekly. Alert if KPI deviates >3σ or >5% relative change.Thresholding & alert rules- Multi-tier alerts: Warning (soft) for early anomalies (PSI 0.15–0.2, 5% perf dip), Critical for confirmed impact (PSI>0.3 + perf drop).- Correlation checks: suppress false positives by requiring at least two related signals (e.g., PSI + rolling accuracy or latency spike + throughput drop).- Rate-limited alerts and escalation: notify data-science on-call via PagerDuty for criticals; Slack for warnings.Dashboards (recommended panels)- Overview: current model metrics, trendlines (7/30/90d), KPI overlay.- Drift panel: PSI/KL per feature heatmap, SHAP importance change.- Feature health: nulls, ranges, cardinality, sample distribution histograms.- Latency/SLO panel: p50/p95/p99, throughput time series, request traces.- Label & feedback: available labeled samples, label delay distribution.- Investigation tools: sample selector, cohort compare, model input snapshot.On-call playbook (triage → remediation)1. Triage (first 10 min) - Acknowledge alert; check dashboard and alert context (which metric, affected cohorts). - Confirm signal: does another metric corroborate? Pull a small labeled sample if available.2. Root-cause hypothesis (10–30 min) - Data issue? Check upstream pipeline, recent schema changes, increased nulls, new categories. - Model issue? Check recent deployments, model weight changes, input distribution shifts, feature importance changes. - Infra issue? Check latency/throughput, resource scaling, downstream service failures.3. Immediate mitigations (30–60 min) - Roll back recent model deploy if available and suspected. - Route traffic to baseline model or shadow mode. - Fix data pipeline or apply input validation/feature filters. - Communicate with stakeholders: product, infra, data engineering.4. Remediation & postmortem (within 48–72 hours) - Implement permanent fix (retrain with recent data, repair ETL). - Update monitoring thresholds, add missing metrics. - Write blameless postmortem with timeline, root cause, action items.5. Escalation - If unable to mitigate in 1 hour, escalate to engineering manager and product owner; if business KPIs impacted, escalate to on-call exec.Best practices- Maintain labeled backlog and automated labeling pipelines to reduce label delay.- Automate daily drift reports and weekly retraining triggers (if drift persistent >7 days).- Version inputs/models, keep feature-store lineage, and run canary deployments.- Log raw inputs and decisions for replay/debug.This plan balances sensitivity vs noise, ties alerts to business impact, and provides clear steps for fast mitigation and learning.
Unlock Full Question Bank
Get access to hundreds of AI and Machine Learning Background interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.