Back to exam

Certified Machine Learning Associate Cheatsheet

Databricks Certified Machine Learning Associate

Download free PDF

Databricks development workflows

Compute and library scope

  • **Databricks Runtime ML** bundles an ML-oriented environment and common libraries, including MLflow. Select an ML runtime when creating compute; record the environment for reproducibility.
  • **Single-node compute** suits data and models that fit one machine. A **multi-node Spark cluster** distributes Spark transformations and supported training algorithms. A SQL warehouse serves SQL workloads.
  • **Notebook-scoped libraries** installed with %pip belong to the notebook environment. Use compute-scoped libraries or supported initialization scripts when dependencies must be available across notebooks on that compute.
  • **Scale up** adds resources to one machine; **scale out** adds workers. More workers help only when the workload distributes and memory, network and scheduling costs remain manageable.

Git collaboration and scheduled work

  • **Databricks Git folders / Repos** connect project files to a remote Git provider. Create a feature branch, edit, commit and push; review and merge changes before updating the production branch.
  • **Notebook revision history** records notebook changes; a Git commit and push publish repository changes to the remote provider. Keep scheduled production jobs on a controlled code reference.
  • **Jobs** orchestrate notebook or other tasks with dependencies and schedules. Inspect the failed run, task graph or matrix view, and task logs to locate failures before rerunning dependent work.

AutoML as a development baseline

  • **AutoML** automates supported preprocessing, candidate model training, hyperparameter search and evaluation. Set the prediction target, problem type, metric and compute budget deliberately.
  • **Generated notebooks** expose the preparation and training code. Inspect the best run and compare alternatives in MLflow; refine preprocessing or search choices when results fall short.
  • **Missing-value handling** in generated pipelines reduces manual preparation, but inspect heavy missingness, unsupported types and leakage. Automation cannot decide whether a feature is valid for the business problem.
  • **Deployment and monitoring** require a separate operational workflow: validate the selected model, package dependencies, register it, serve predictions and monitor results.

Data preparation and feature engineering

Distributed DataFrame exploration

  • **Spark DataFrames** support distributed SQL-style transformations. For example, df.filter(col("price") > 0) retains positive prices. Use Spark expressions for scalable filtering and derived columns.
  • **summary()** returns count, mean, standard deviation, extrema and selected percentiles. **describe()** gives basic summaries; **printSchema()** shows types. Compute **IQR = Q3 − Q1** from the quartiles.
  • **dbutils.data.summarize(df)** provides Databricks data profiling, including visual distributions. Spark DataFrame summary operations are the portable choice when running outside Databricks.
  • **pandas API on Spark**, imported as pyspark.pandas, offers familiar pandas syntax over Spark execution and additional metadata. Convert with df.pandas_api(); inspect costly index, shuffle and ordering operations.
  • **toPandas()** collects data into driver memory. pandas API on Spark remains distributed, but pandas compatibility does not guarantee better speed than native Spark expressions.

Missing values and robust summaries

  • **Mean imputation** uses the numeric average; **median imputation** resists extreme values. Use the **mode** or an explicit missing category for categorical data when appropriate.
  • **Missingness indicators** preserve information about which values were absent after imputation. Fit imputation statistics on training data and reuse them for validation, test and inference.
  • **Spark Imputer** is an Estimator: fit it to obtain an **ImputerModel**, then transform numeric columns. Median estimation can use approximate quantiles; exact global medians require more coordination than means.
  • **IQR outlier fences** are Q1 − 1.5 × IQR and Q3 + 1.5 × IQR. They flag unusual values, not automatic errors; validate their meaning before removing observations.
  • **Time-series imputation** must use information available at prediction time. Respect sensor identity, seasonality and chronology; a full-day statistic can leak later measurements into earlier predictions.

Encoding and preprocessing pipelines

  • **One-hot encoding** represents categories with binary indicators. It suits nominal categories without imposing a numeric order; high cardinality can produce very wide feature vectors.
  • **StringIndexer → OneHotEncoder → VectorAssembler** is a common Spark feature path. Assemble encoded and numeric inputs into the vector column expected by Spark ML estimators.
  • **Identifiers** are usually join keys, not useful numeric predictors. Treat postal codes as categorical geography rather than magnitudes; choose a representation that controls cardinality and generalizes.
  • **StandardScaler** learns training statistics; its fitted model transforms later data consistently. Scaling can matter for distance-based or regularized models, while tree splits generally do not require it.
  • **scikit-learn ColumnTransformer** applies separate numeric and categorical pipelines, such as imputation plus scaling versus imputation plus one-hot encoding. Chain the combined preprocessing with the estimator.
  • **Target encoding** uses label information and needs leakage-safe fitting, such as out-of-fold training encodings. Keep reusable feature tables broadly useful; model-specific encoding can belong in the training pipeline.

Reusable features and governed tables

  • **Feature tables** store reusable features with lookup keys and metadata. The workspace **FeatureStoreClient** and Unity Catalog **FeatureEngineeringClient** serve different feature-management contexts.
  • **Unity Catalog** organizes governed data as catalog.schema.table and supports discovery across authorized workspaces. An eligible Delta table with declared primary keys can serve as a feature table without duplicating its data.
  • **Primary keys** identify feature rows; ensure their columns are non-null and values are unique. A declared informational constraint does not replace data-quality checks.
  • **create_table** creates feature-table metadata and can populate it from a DataFrame. **write_table(name=..., df=...)** writes to an existing table; choose merge or overwrite deliberately rather than redeclaring the key.
  • **Table metadata** includes descriptions and keys. In the workspace Feature Store API, fs.get_table(name).description retrieves the description; feature data and table metadata are separate objects.

Training lookups and online access

  • **FeatureLookup** describes the table, feature names and lookup keys. **create_training_set** joins base examples to one or more feature tables; load the resulting DataFrame for training.
  • **Lookup keys and renamed outputs** let one source feature play different roles, such as origin and destination. Avoid duplicate output names and keep keys aligned with the intended entity.
  • **Feature-aware model logging** records training-set lookup metadata. A compatible **score_batch** workflow can retrieve recorded features from input keys; simply loading an ordinary model does not infer arbitrary joins.
  • **Offline feature tables** support historical training and bulk access. **Online feature stores** optimize low-latency keyed retrieval for real-time inference; feature freshness is separate from online model learning.

Model training and hyperparameter tuning

Spark ML objects and algorithms

  • **Estimator.fit(df)** learns from data and returns a fitted Transformer. **Transformer.transform(df)** returns a transformed DataFrame. A fitted prediction model is a Transformer.
  • **VectorAssembler** is a Transformer; **StandardScaler**, **Imputer** and **LogisticRegression** are Estimators. A **Pipeline** chains stages; fitting it produces a **PipelineModel**.
  • **Spark ML** distributes supported feature engineering and model fitting over Spark data. A scikit-learn model does not become distributed merely because its Python code runs on a cluster.
  • **Linear regression** minimizes a regression objective. Spark can use a normal-equation solver where suitable or iterative optimization; the solver choice depends on dimensionality, settings and implementation constraints.
  • **Spark decision trees** bin continuous values into candidate splits. Results can differ from scikit-learn despite similar parameters. **maxBins** must accommodate categorical cardinality; raising it increases computation.

Ensembles, bias and variance

  • **Bagging** trains models on bootstrap samples and aggregates their predictions. **Random forests** also randomize feature selection, reducing correlation among trees; trees can be trained independently.
  • **Boosting** adds learners sequentially to improve the current ensemble. Later learners depend on earlier results, limiting parallelism across boosting rounds even when work inside a round is distributed.
  • **Stacking** trains a combining model on base-model predictions, using out-of-fold predictions to avoid leakage. **Conditional routing** selects a specialist model by a rule, such as a feature range.
  • **Inference cost** depends on how many models execute per record. Aggregating every model adds work; routing may execute only one specialist. Measure latency, throughput and model-loading costs.
  • **High variance / overfitting** often appears as strong training performance and weak validation performance. **High bias / underfitting** often gives poor performance on both; use suitable complexity, regularization and data.

Search spaces and objectives

  • **Hyperparameters** control model structure or training behavior; learned parameters come from fitting. Define valid categorical, integer and continuous search spaces, including compatible parameter combinations.
  • **Grid search** exhausts combinations; **random search** samples configurations. scikit-learn uses **GridSearchCV** and **RandomizedSearchCV** respectively. Random search can spend a fixed trial budget across broad ranges.
  • **TPE**, the tree-structured Parzen estimator, proposes configurations using previous trial outcomes. It is useful when trials are costly and the space mixes discrete and continuous choices.
  • **Hyperopt fmin** minimizes an objective. Return validation error directly, or negate a score such as R² or F1 that should be maximized. Keep the final test set outside the tuning objective.
  • **Hyperopt search spaces** use hp.choice for choices, hp.uniform for a continuous range and hp.loguniform for a log-scaled range. Quantized samples may need explicit integer casting for model parameters.
  • **max_evals** limits trial count; time budgets also depend on per-trial duration and concurrency. More trials explore more configurations but cannot guarantee an improvement.

Distributing trials and validation

  • **Hyperopt Trials** runs an ordinary local trial loop. **SparkTrials** schedules independent single-node objective evaluations on Spark workers; each trial still needs enough memory for its own data and model.
  • **Distributed Spark ML objectives** already use the cluster for model fitting. In Hyperopt workflows, use a driver-side Trials loop for these objectives rather than nesting Spark ML jobs inside SparkTrials worker tasks.
  • **Optuna trial distribution** also needs an execution backend or distributed orchestration, such as the Joblib Apache Spark backend. Experiment tracking alone does not schedule trials across workers.
  • **Parallelism versus adaptation:** launching the whole budget at once leaves few completed outcomes to guide TPE. Use enough sequential rounds to learn while balancing elapsed time and compute utilization.
  • **Memory limits concurrency.** Concurrent local trials share worker resources; doubling tasks can cause contention or out-of-memory errors. Also control each model library’s internal thread count.
  • **Grid workload** equals the product of candidate counts × validation folds. A 4 × 3 × 2 grid with 5 folds needs 120 fold fits, plus a final fit when refit is enabled; available resources limit simultaneous fits.

Validation and model evaluation

Splits, folds and leakage

  • **randomSplit([0.8, 0.2], seed=...)** creates random Spark training and test partitions with approximate proportions. Persist split datasets or stable key assignments when exact membership must survive execution changes.
  • **Train / validation / test** separate fitting, selection and final assessment. **k-fold cross-validation** averages validation scores across folds; keep a final holdout untouched by repeated model choices.
  • **Cross-validation** usually gives a more stable estimate than one split but requires more fits. A train-validation split can be preferable when compute is expensive or the dataset is sufficiently large.
  • **Fit preprocessing within each training fold.** Cross-validate the whole pipeline when scaling, imputation or encoding learns from data. Pre-fitting these stages on all folds risks validation leakage.
  • **Preprocessing reuse** can reduce repeated work, but moving cross-validation behind a fitted preprocessing pipeline changes the leakage boundary. Cache safe intermediate data and preserve fold-specific learned transformations.
  • **Time-series evaluation** trains on earlier observations and validates on later ones using rolling or expanding windows. Keep future labels, future-derived features and inappropriate random shuffling out of training.

Classification and imbalance

  • **Precision = TP / (TP + FP)** measures how trustworthy positive predictions are. **Recall = TP / (TP + FN)** measures how many actual positives are found; prioritize recall when missed positives are costly.
  • **Accuracy = correct / total** can hide poor minority-class detection. **F1 = 2PR / (P + R)** balances precision and recall but ignores true negatives; choose the positive class and averaging method deliberately.
  • **ROC-AUC** measures ranking across decision thresholds; **PR-AUC** emphasizes positive-class precision and recall. Neither alone proves production readiness: inspect thresholds, error costs and subgroup performance.
  • **Class imbalance** can be addressed with class weights, minority oversampling or majority undersampling. Apply resampling inside training folds; preserve the deployment class distribution in validation and test data.
  • **Spark evaluators** require matching label and prediction columns. Use **MulticlassClassificationEvaluator** for accuracy or multiclass F1, and **BinaryClassificationEvaluator** with scores for binary ranking metrics.

Regression metrics and diagnostics

  • **MSE** averages squared errors; **RMSE = √MSE** has target units and penalizes large errors strongly. **MAE** averages absolute errors and is less sensitive to extreme errors. Lower is better for all three.
  • **R² = 1 − SSE / SST** compares squared error with predicting the evaluation-set mean. Higher is better; it can be negative and does not establish causality or guarantee useful out-of-sample predictions.
  • **RegressionEvaluator** supports metrics such as rmse, mse, mae and r2. Set labelCol to the actual-label column and predictionCol to the prediction column rather than relying on mismatched defaults.
  • **Log-target models** predict on the log scale. Invert the transformation on predictions before computing RMSE against original-scale targets; exponentiating an already computed RMSE is not equivalent.
  • **Loss functions** determine training updates and error sensitivity; evaluation metrics assess results. A log transform can reduce positive-target skew or unequal residual variance, but inspect residuals and original-scale performance.
  • **Linearity** can be explored with predictor-versus-target plots and residual plots. Check independent errors and roughly constant residual variance; normal-error assumptions matter chiefly for classical inference.
  • **Association tests** depend on variable types: a chi-square test assesses association between categorical variables; Pearson correlation measures linear association between numeric variables. Association alone does not establish confounding or causality.

MLflow tracking and production inference

Experiments, runs and artifacts

  • **MLflow experiments** group runs. Runs record parameters, metrics, tags, artifacts and execution metadata; compare multiple runs to understand performance and parameter trade-offs.
  • **Manual logging** uses a with mlflow.start_run() context with log_param, log_metric and a model-flavor log_model call. Disable autologging when complete control over recorded fields is required.
  • **Autologging** records supported framework details automatically. Inspect what is captured rather than assuming every library, artifact or business metric is logged.
  • **Nested runs** organize a tuning parent and its trials: start the parent, then call start_run(nested=True) for each child. Sharing an experiment alone does not establish parent-child relationships.
  • **Artifacts** are files, such as feature-importance CSVs or plots. Write the DataFrame to a file and call log_artifact(local_path); log_metric records a scalar numeric value, not an entire table.
  • **Run provenance** includes start time, duration and source information. A notebook source link identifies associated code; the MLmodel artifact instead describes a logged model’s flavors and metadata.

Run search and model packaging

  • **mlflow.search_runs** queries experiment IDs and returns run information. Resolve an experiment name to its ID, order by the desired metric, and select the best eligible run.
  • **Metric direction matters:** order RMSE ascending and F1 or R² descending. Verify that compared runs use the same dataset, split strategy, label scale and metric definition.
  • **Model URIs** identify artifacts: runs:/<run_id>/model addresses a model logged under that artifact path. A registered model version provides a stable catalog entry for lifecycle management.
  • **Model signature** records input/output schema; an input example illustrates valid requests. Record required packages with pip_requirements or extra_pip_requirements and ensure private dependencies are accessible to serving compute.

Registry, aliases and lineage

  • **mlflow.register_model(model_uri, name)** registers a logged artifact. Registering under an existing name creates another model version; registered_model_name in supported log_model calls can combine logging and registration.
  • **Unity Catalog registration** uses a three-part catalog.schema.model name. Set the registry URI to databricks-uc when explicitly targeting it, supply the required model signature and use an identity with appropriate privileges.
  • **Workspace registry stages**, such as Staging and Production, belong to a stage-based lifecycle. Inspect or request a stage transition on the relevant model version according to permissions and review policy.
  • **Unity Catalog aliases** are movable references to model versions. Use set_registered_model_alias(name, alias, version) for champion/challenger automation; consumers can resolve models:/<name>@Champion.
  • **Registered-model tags** use name, key and value; version tags additionally identify a version. Tags classify metadata, while aliases resolve versions. A PII approval tag does not enforce access control.
  • **Unity Catalog lineage and permissions** connect governed data and model workflows. Capture training inputs and model metadata so lineage can be recorded; registration alone cannot reconstruct every untracked external dependency.

Spark batch and streaming inference

  • **Native Spark ML models** transform distributed DataFrames. For a single-node model such as scikit-learn, a **pandas UDF** or MLflow pyfunc.spark_udf can distribute predictions over Spark partitions.
  • **pandas UDFs** exchange Arrow batches with Python and run vectorized pandas operations. They reduce per-row Python overhead; prefer native Spark expressions where they already express the computation.
  • **Iterator pandas UDFs** can initialize a model once per iterator invocation and reuse it across batches. Worker processes and tasks may initialize separately; do not assume exactly one model copy per executor.
  • **Column arguments** must match the UDF contract and model schema. Expanding column names with predict(*df.columns) passes separate column arguments; preserve the training feature order and output data type.
  • **groupBy(key).applyInPandas(function, schema)** supports group-specific training or inference. **mapInPandas** processes partition batches. Grouped operations shuffle data, and a large group can exhaust worker memory.
  • **Streaming inference** scores arriving data with a fixed model through a compatible transformation or microbatch function. In DLT-style pipelines, read_stream supplies streaming input; model retraining is a separate process.

Deployment, serving and traffic

  • **Deploy model** promotes a validated artifact, useful when training is expensive or difficult to repeat. **Deploy code** promotes a reproducible training workflow, useful when training must run against protected production data.
  • **Batch inference** scores accumulated data on a schedule. **Streaming inference** scores arriving events or microbatches; **real-time serving** handles synchronous requests. Choose by freshness, latency, throughput and cost.
  • **Serving traffic splits** route request percentages among served models for A/B or champion/challenger evaluation. A 70/15/15 split divides traffic rather than averaging all three models’ predictions.
  • **Scale to zero** can reduce idle serving cost where supported, with cold-start latency on resumed traffic. Choose endpoint capacity and scaling behavior against the application’s response-time needs.
  • **Production validation** includes schema and dependency tests, data quality, latency and outcome metrics. Monitor input drift and predictive performance when labels arrive; drift alone does not prove that retraining improves results.