Back to exam

Certified Machine Learning Professional Cheatsheet

Databricks Certified Machine Learning Professional

Download free PDF

MLflow tracking and model packaging

Experiments, runs and nested trials

  • An **experiment** groups runs; a **run** records one training or evaluation execution. Use meaningful names and tags for algorithm, dataset, owner and purpose.
  • Start a parent with **mlflow.start_run()**, then start child runs inside its active context with **nested=True**. A shared run name does not establish parentage.
  • Organize algorithm comparisons as parent runs and hyperparameter trials as children. Record trial status, validation results and the selected model so selection remains traceable.
  • **mlflow.autolog()** enables supported library integrations; training calls such as **fit()** trigger logging. Explicitly log custom metrics, plots and other information the integration omits.

Parameters, metrics and artifacts

  • **log_param(key, value)** records a setting; **log_params(dict)** records several. Treat a parameter as fixed within a run; use a new run for changed configurations.
  • **log_metric(key, number)** records an outcome; **log_metrics(dict)** records several. Steps and timestamps support metric histories, unlike a single configuration value.
  • **log_artifact(local_path)** uploads a file such as a CSV, PDF or PNG. Its optional **artifact_path** is a destination directory, not a replacement filename.
  • **log_figure(figure, filename)** logs a supported in-memory plot. Artifacts appear on the run's artifact view; uploading a CSV does not turn its columns into tracked metrics.
  • Flatten nested configuration keys for searchable parameters and save the complete configuration as an artifact. Keep credentials and sensitive records out of tracking data.

Querying results and choosing models

  • **mlflow.search_runs(experiment_ids=[exp_id])** returns a pandas DataFrame by default. Filter by parameters, metrics and tags; specify metric ordering when selecting candidates.
  • **MlflowClient.get_run(run_id).data.metrics** exposes a run's recorded metric values. Use **get_metric_history()** when the sequence of values matters.
  • The Databricks **mlflow-experiment** Spark data source can expose experiment results as a Spark DataFrame: **spark.read.format("mlflow-experiment").load(exp_id)**.
  • Select the best candidate using the intended **validation metric**, direction and constraints. Lower RMSE is better; higher AUC is better. Training loss alone is a poor promotion criterion.
  • Record code revision, data snapshot, dependencies and evaluation protocol with the selected run. **Test data** should provide a final unbiased assessment rather than guide repeated tuning.

Flavors, signatures and custom models

  • A model **flavor** describes how to save and load a model. **mlflow.sklearn.load_model()** restores a scikit-learn object; **mlflow.spark.load_model()** restores a Spark model.
  • **mlflow.pyfunc.load_model()** offers a common **predict()** interface across compatible model flavors. Use a native loader when you need attributes such as **feature_importances_** or Spark **featureImportances**.
  • **infer_signature(example_inputs, example_outputs)** describes input and output schemas. Log the **signature** and an **input_example** with the model to document and validate its serving contract.
  • Wrap custom inference in **mlflow.pyfunc.PythonModel**. Reuse preprocessing during training and prediction; a logged inference wrapper does not automatically expose a training **fit()** interface.
  • Package tokenizers, encoders, weights and configuration through the model's **artifacts** mapping. Load them via **load_context(context)** and **context.artifacts**; package code and software dependencies separately.
  • Model logging, **log_artifact()**, and model registration serve different purposes. A file attached to a run is not automatically an artifact dependency of a deployable custom model.

Delta data and feature engineering

Delta tables, history and reproducibility

  • **spark.read.format("delta").load(path)** reads a Delta path; **spark.read.table("catalog.schema.table")** reads a named table. A filesystem path and a table identifier are different inputs.
  • **df.drop("column")** returns a new DataFrame without that column. It does not change the stored table unless the result is explicitly written or a table alteration is performed.
  • **DESCRIBE HISTORY table_name** exposes transaction history. Use operation details to investigate table changes; retain the data versions needed for reproducible training.
  • **option("versionAsOf", 0)** reads the first Delta snapshot when its files and log remain available. Time travel depends on retention; it is not a substitute for a backup policy.
  • **OPTIMIZE** compacts small files. **Z-Ordering** colocates related values to improve selective reads through data skipping; it addresses a different issue from file size alone.

Feature tables and update semantics

  • A **feature table** stores reusable features with declared lookup keys. Unity Catalog uses governed Delta tables and primary-key metadata; verify actual key uniqueness and null handling in the data.
  • Use the **FeatureEngineeringClient** for Unity Catalog feature workflows and **FeatureStoreClient** for workspace feature workflows. Table names and permissions must match the chosen store.
  • **create_table()** defines a feature table and can populate it from a DataFrame. **read_table()** returns its data; **get_table()** retrieves metadata rather than the feature rows.
  • **write_table(..., mode="merge")** updates matching keys and inserts new keys while retaining unmatched rows. A merge does not remove records merely because they are absent from the incoming batch.
  • Distinguish an incremental **upsert** from a complete snapshot replacement. Validate schema, key coverage and deletion policy before replacing persisted features.

Training sets and temporal correctness

  • **FeatureLookup** describes feature names, source tables and lookup keys. **create_training_set()** joins lookups to labeled examples and records feature lineage for later scoring.
  • Use **point-in-time lookups** with a **timestamp_lookup_key** for historical examples. Match the latest feature record at or before the example's prediction timestamp.
  • Future sensor readings, end-of-day aggregates and features computed after the outcome can cause **label leakage**. Temporal validity includes when the information was actually available.
  • Log a feature-aware model with its **training_set** metadata. **score_batch(model_uri, input_df)** can retrieve required features using the logged lookup specification.
  • Supply lookup keys and required request-time inputs when scoring. Explicitly supplied feature columns can override looked-up values; test this behavior and column contracts before production use.

Online and on-demand features

  • **Offline tables** support large training and batch workloads. **Online stores/tables** support low-latency key lookups; publishing introduces synchronization, freshness and access-control requirements.
  • **Continuous synchronization** keeps processing changes; **triggered synchronization** runs on demand or a schedule. A **snapshot** copies a full state rather than incrementally maintaining every change.
  • Combine streaming ingestion with online publication when recent events must be available for lookups. Updating an offline Delta table alone does not provide an online serving path.
  • A Unity Catalog **FeatureFunction** can describe request-time computation alongside **FeatureLookup** dependencies. Feature-aware logging preserves the lookup and computation contract for inference.
  • On-demand functions must handle **None**, **NaN**, missing keys and invalid inputs. Reuse the same transformations offline and online to reduce **training-serving skew**.

Scalable training and hyperparameter tuning

Choosing compute and parallelism

  • Use **single-node Python** when data and training state fit comfortably in memory. Scheduled batch work usually needs less infrastructure than an always-on endpoint for the same daily deadline.
  • Choose **Spark ML** for supported algorithms requiring distributed training over large data. Adding workers does not distribute a pandas DataFrame or ordinary scikit-learn estimator automatically.
  • **Data parallelism** partitions training examples for one coordinated model. Training many independent models is task parallelism; splitting one model's components is **model parallelism**.
  • Investigate partition skew, per-task memory and algorithm state before scaling. More executors do not repair a single oversized group or an algorithm that requires all data locally.
  • Use **Spark** for large joins and cleansing, then a suitable distributed framework such as **Ray Train** or a supported PyTorch distributor for deep learning. Allocate GPUs to training workers and match dependencies across them.

Independent models with pandas functions

  • **groupBy("key").applyInPandas(function, schema)** sends each group to a pandas function. It suits independent models per customer, sensor, region or product using existing Python libraries.
  • Each group must fit worker memory; group size imbalance creates **stragglers** or failures. Tune partitioning and resource allocation instead of collecting the complete dataset to the driver.
  • A grouped pandas function returns a **pandas DataFrame** conforming to the declared Spark schema, not an arbitrary model object. Persist models or return model identifiers, metrics and predictions deliberately.
  • **mapInPandas()** processes partition batches without guaranteeing logical groups. Use grouped execution when a model requires all records for a specific entity.
  • **pandas UDFs** can vectorize batch prediction. Load or select the correct trained model per worker and key; partitioning alone does not route each record to its model.

Spark ML pipelines and evaluation

  • A Spark **Transformer** uses **transform()**; an **Estimator** learns through **fit()**. **Pipeline(stages=[T1, T2, E1]).fit(trainingDF)** returns a **PipelineModel** that transforms test data.
  • Order preprocessing before the estimator: **StringIndexer**, **OneHotEncoder**, vector assembly and required scaling. Configure **handleInvalid="skip"** on supported indexing stages when unseen categories must be dropped.
  • **MinMaxScaler** scales each fitted feature range toward [0,1]; **StandardScaler** uses variance and optionally mean. New values beyond fitted extrema can exceed the MinMax training range.
  • Use **BinaryClassificationEvaluator** for ROC-AUC or PR-AUC on scores, **MulticlassClassificationEvaluator** for multiclass metrics, and **RegressionEvaluator** for RMSE, MAE or R2.
  • Evaluate several regression metrics by calling **evaluate()** with different **metricName** settings. Multiclass channel prediction requires classification; numeric channel codes do not make it regression.

Search strategies and tuning resources

  • **Grid search** enumerates combinations; **random search** samples them. **Bayesian/TPE search** uses previous outcomes to guide new trials and can reduce wasted evaluations.
  • Spark **ParamGridBuilder** defines candidates. **CrossValidator** repeats fitting across folds; **TrainValidationSplit** uses one split and is cheaper. Use time-respecting validation for forecasting.
  • **Ray Tune** manages trials, search spaces and optimization metrics; **Ray Train** manages training execution. A search algorithm proposes configurations; a scheduler controls trial continuation or early stopping.
  • Replacing a Tune grid with Bayesian search requires a compatible sampled search space and **search_alg**, plus the correct **metric** and **mode**. Merely renaming the trial function does not change search behavior.
  • Set per-trial CPUs/GPUs and concurrency within cluster limits. **Optuna TPE** is a common single-objective adaptive sampler; explicitly configure a sampler when reproducibility requires it.
  • For distributed MLflow logging, propagate the tracking URI, experiment and secure authentication to workers. Configure **DATABRICKS_HOST** and authorized credentials before Ray workers start when that authentication path is used.

Batch, streaming and real-time inference

Choosing a deployment pattern

  • **Batch inference** computes predictions ahead of consumption and stores results. It suits known features, periodic deadlines and large prediction sets that can be queried later.
  • **Streaming inference** scores incrementally arriving data and writes results as processing advances. It provides continuous updates without requiring a synchronous response for each external request.
  • **Real-time serving** scores request-time inputs through a central endpoint. It suits transaction decisions requiring one response immediately; include feature lookup time in the latency budget.
  • **Edge/on-device inference** computes near the user or device, reducing network dependence. Consider device resources, model distribution and update management.
  • For rarely accessed annual predictions, durable **object storage/Delta tables** avoid maintaining always-on serving compute. Precomputed results can still be delivered quickly through a suitable query layer.

Distributed scoring and streaming reliability

  • A native **Spark ML PipelineModel.transform(df)** runs Spark transformations over distributed data. Use it directly for a logged Spark pipeline loaded with **mlflow.spark.load_model(model_uri)**.
  • **mlflow.pyfunc.spark_udf(spark, model_uri, result_type=...)** adapts a compatible model for distributed Spark scoring. Match input order, schema and return type to the logged model contract.
  • **spark.readStream** creates a streaming DataFrame; **writeStream** persists results. A trigger controls processing cadence, but microbatch sizes depend on arrival rates and source limits.
  • Validate input schemas and malformed records, use durable **checkpoints**, and make sink operations retry-safe. **foreachBatch** can apply batch scoring logic to each microbatch.
  • Handle **late/out-of-order events**, event-time windows and watermarks explicitly. A streaming framework's recovery guarantees do not automatically make external side effects exactly once.

Serving contracts and integrations

  • **Model Serving** exposes a deployed entity through an endpoint. The endpoint name, registered model name and model version identify different things; configure the intended entity explicitly.
  • Invoke endpoints through the **REST API**, Python **MLflow Deployments SDK**, or SQL **ai_query()** where supported. Use the endpoint's expected payload schema, such as **dataframe_split**.
  • **get_deploy_client("databricks").predict(endpoint=..., inputs=...)** is the Python deployment-client pattern. A registry **models:/...** URI is not an HTTP invocation URL.
  • Package preprocessing, model artifacts and pinned dependencies together. A **container** bundles application software and libraries, but model-serving access to external systems still requires authentication and network connectivity.
  • For external credentials, use serving environment variables backed by secret references such as **{{secrets/scope/key}}**. Read the variable inside the model; never bake its resolved value into an artifact.

Latency, capacity and rollout

  • **Scale to zero** saves idle capacity but introduces cold starts. Keep warm capacity when stable low latency matters even at a low request rate.
  • **Horizontal scaling/concurrency** addresses simultaneous demand; larger hardware addresses per-request resource constraints. Correlate request rate, queueing, GPU utilization, memory and latency before changing capacity.
  • **P50** is the median latency; **P95/P99** describe the tail. Compare endpoint metrics with end-to-end client timing, which also includes network and application overhead.
  • **Load tests** should reproduce expected request rate, concurrency, payload sizes and warm/cold behavior. Record errors and tail latency rather than relying on training-time metrics.
  • **Blue-green** prepares a healthy replacement and switches traffic with a ready rollback path. **Canary** gradually exposes a small traffic share; **shadow** evaluates a copy without using its results for user decisions.

Model governance and MLOps delivery

Registry objects, versions and access

  • **MLflow Tracking** records experiments; the **Model Registry** manages named models and their versions. Registering another artifact under an existing name creates another model version.
  • Register a logged model using **mlflow.register_model(model_uri, name)** or a flavor logger's **registered_model_name**. A run artifact URI has the form **runs:/run_id/artifact_path**.
  • Unity Catalog model names use **catalog.schema.model**. Govern access through the catalog and schema, model privileges and service identities; include a model signature for registration.
  • In the **workspace registry**, stages are **None, Staging, Production, Archived**. Unity Catalog uses **aliases** such as **Champion** instead of these stages; aliases point to chosen versions.
  • Use **update_registered_model()** for model-level descriptions and **update_model_version()** for version-level descriptions. **delete_model_version()** removes one version; **delete_registered_model()** removes the named model and its versions.

Promotion and reproducible environments

  • **Deploy code** promotes tested training and inference source code, then trains in the target environment. **Deploy model** promotes an already trained artifact; choose based on data access and training constraints.
  • Keep **development, staging and production** isolated. When production data is restricted, execute approved training code with an authorized production service principal rather than copying a model trained only on sanitized development data.
  • Pin runtime and package dependencies with a lock or requirements file. Capture feature definitions and data versions; using the same runtime alone does not pin private PyPI packages.
  • **Databricks Asset Bundles** express jobs and related ML resources as code with environment targets. **Terraform** can manage platform resources and policies; store configuration in version control.
  • Use shared governance, project boundaries, least privilege and compute policies for large teams. Cost attribution and resource limits require managed policy rather than user naming conventions alone.

Tests and maintainable project structure

  • Put reusable functions in **Python modules** and tests in a separate suite; keep notebooks focused on orchestration and exploration. Imports do not automatically execute tests.
  • **Unit tests** validate transformations and model logic using small deterministic fixtures. Test a new feature's expected calculation, edge cases and missing values before expensive pipeline execution.
  • **Integration tests** verify interactions across feature creation, training, evaluation, registration, deployment and inference. Include schema contracts, feature lookup and artifact loading.
  • Run fast unit tests first and production-like integration tests in **staging** as CI gates on pull requests. Use small representative data and reduced training iterations while preserving the pipeline's structure.
  • Add **performance/load tests** for serving latency and throughput. Functional integration success does not establish capacity, prediction quality or fairness under production conditions.

Automation and safe refresh

  • The **Jobs REST API** creates and runs jobs programmatically; job identifiers are available from job details and API responses. Use automated compute and event/table-update triggers where they meet freshness needs.
  • Registry **webhooks** can react to model-version events in supported workspace registry workflows. Job webhooks invoke jobs; HTTP webhooks notify external services. Do not assume the same event mechanism applies to Unity Catalog.
  • For workspace stage transitions, **transition_model_version_stage(..., archive_existing_versions=True)** can archive prior versions in the destination stage. Stage changes and serving traffic configuration are distinct operations.
  • A refresh pipeline trains candidates, evaluates on representative recent held-out data, registers a qualified candidate and deploys after tests. Newer data alone does not establish superiority.
  • Preserve a tested rollback artifact and record deployed model versions. An alias or stage change should follow approval criteria, not bypass quality, compatibility and operational gates.

Production monitoring and drift

Drift vocabulary and diagnosis

  • **Feature drift** changes the input distribution **P(X)**. Out-of-range temperatures, changed transaction amounts and new categories can indicate feature drift.
  • **Label drift** changes the observed target distribution **P(Y)**, such as a changed fraud prevalence. **Prediction drift** changes the distribution of model outputs.
  • **Concept drift** changes the relationship **P(Y|X)**, such as transaction frequency becoming less predictive of fraud. It cannot be established solely from an input histogram.
  • Compare predictions with delayed **ground-truth labels** to track efficacy. Performance decline can also arise from bad joins, schema changes, missing features or operational failures.
  • Drift is a signal to investigate, not proof of harmful model behavior. Examine representative windows, affected slices, business impact and data quality before retraining or retiring an application.

Statistics for numerical and categorical data

  • For numerical inputs, trend **mean, variance, quantiles, range and missingness** as low-cost signals. Distribution tests reveal changes that summary statistics can miss.
  • The **two-sample KS test** compares empirical cumulative distributions of numeric data. A larger statistic indicates greater separation; a small p-value is evidence against equal distributions.
  • **Wasserstein distance** measures distribution displacement in the variable's units. **Jensen-Shannon distance** symmetrically compares distributions; numeric applications need consistent binning and smoothing.
  • For categorical features, track **category frequencies, mode, cardinality and missing percentage**. Treat missingness as an explicit category or test missing/not-missing rates directly.
  • **Chi-squared goodness-of-fit** compares observed counts with expected proportions; a **contingency-table test** compares category distributions across samples. Check sample-size and expected-count assumptions.
  • **Total variation** and consistently normalized **JS distance** provide bounded distribution comparisons. Set effect-size thresholds with context; p-values are sample-size sensitive and no cutoff is universal.

Monitor profiles and metric interpretation

  • **Snapshot** profiles summarize a table's state; **TimeSeries** profiles aggregate by timestamp windows; **InferenceLog** profiles add model prediction and performance analysis over time.
  • An inference monitor needs a timestamp, prediction column, model identifier and correct **classification/regression** problem type. Provide a label column when ground truth is available.
  • **Profile metrics** summarize a window or slice. **Drift metrics** compare windows or a baseline; select the relevant table instead of expecting every metric in the profile output.
  • **BASELINE drift** compares with a selected reference dataset; **CONSECUTIVE drift** compares adjacent windows. Check the feature, model, slice, time window and comparison type before interpreting a result.
  • Use a representative reference such as training or initial evaluation data. Keep window sizes and baseline choices deliberate; a moving recent baseline can conceal gradual long-term drift.

Performance, fairness and response

  • Join inference records to outcomes with a stable business identifier. Supplying **client_request_id** can connect an inference log to later labels; timestamps alone are unreliable join keys.
  • Track **precision and recall** for the important class, not overall accuracy alone. Monitor regression **RMSE/R2** and label completeness; delayed outcomes can bias recent-window comparisons.
  • Use **slicing expressions** for feature groups and explicit intersections. Compare group sample sizes as well as metrics; aggregate accuracy can conceal poor performance for a subgroup.
  • **Demographic parity** compares positive prediction rates; **equal opportunity** compares true-positive rates; **predictive parity** compares positive predictive value. Fairness criteria can conflict.
  • Custom **aggregate metrics** summarize rows, **derived metrics** combine aggregates, and **drift metrics** compare summaries. A weighted composite score and its change are separate monitoring calculations.
  • Schedule **SQL alerts** on the appropriate metric tables and configure notifications or a webhook-driven retraining workflow. Include persistence checks and validation gates before a retrained model replaces production.