ML Best Practices
I want to read a story about the data, not just run code. Ensure every code cell
is followed by a markdown cell analyzing the results. End the notebook with a
summary comprehensively answering the prompt.
If there is a good match between the user's request and a corresponding example
plan, then adapt the example plan to fully answer the user's request:
Clustering:
Identify distinct groups based on their features.
- Understand the schema and field descriptions.
- Visualize features referenced in the prompt (e.g., with histograms,
scatterplots).
- Transform dates into timestamps.
- Before applying encoders, check if the dataset already contains pre-encoded
features and prefer existing numerical representations.
- Prefer to keep data instead of dropping it when possible.
- Transform ordinal data with an ordinal encoder.
- Transform nominal data with a one hot encoder.
- Standardize numerical features.
- Perform clustering with a range of values, and collect the silhouette score.
- Choose the optimal number of clusters based on the silhouette score.
- Use dimensionality reduction (e.g., PCA) to project the data into two
dimensions.
- Scatterplot the samples in two dimensions with cluster labels as the hue.
- Scatterplot the samples in two dimensions with a discrete feature as the
hue.
- Describe the clusters in text by feature distributions or typical feature
values.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Time Series Forecasting:
Develop a predictive model to estimate future values based on historical trends.
How might different modeling approaches impact the prediction accuracy?
- Understand the schema and field descriptions.
- Visualize the target feature over time at a reasonable granularity.
- Always perform a chronological split on the data to create training,
validation, and test sets.
- Are there seasonal trends?
- Test for stationarity.
- Discuss possible modeling approaches. How might different modeling
approaches impact the prediction accuracy?
- Train two time series forecasting models to predict the target feature. Use
previous seasonality and stationarity information as model hyperparameters.
- Predict the target feature for the training and validation sets.
- Optionally, hypertune models with the validation set.
- Visualize the actual and predicted target feature vs time for each model on
the training and validation sets.
- Evaluate the validation performance with error metrics.
- Select a model.
- Retrain the selected model on the test and validation sets.
- Predict the test values with the selected model.
- Visualize the average target feature and the predicted test values.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Exploratory Data Analysis / Anomaly Detection:
Identify and describe any outliers, unusual patterns, or significant trends
observed in the data. Provide visualizations to support your findings.
- Understand the schema and field descriptions.
- Visualize the target feature distribution in a way that shows outliers.
- Identify and describe any outliers in the target feature.
- Visualize relationships between the target feature and other features.
- Identify and describe unusual patterns or significant trends.
- Visualize patterns and trends.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Classification:
Given the data, can we classify by the target feature?
- Understand the schema and field descriptions.
- Identify rows that don't make sense. How many are there and what do they
contain?
- Identify rows without a target value. How many are there and what do they
contain?
- Drop rows that don't match the schema or don't have the target value (if it
is reasonable to do so).
- Split data into training, validation, and test sets.
- Create features to represent when data are missing, if this is meaningful.
- Handle missing data. Prefer to keep data instead of dropping it when
possible.
- Before applying encoders, check if the dataset already contains pre-encoded
features and prefer existing numerical representations.
- Transform ordinal data with an ordinal encoder.
- Transform nominal data with a one hot encoder.
- Standardize numerical features.
- Train multiple models.
- If there is evidence of overfitting, regularize and retrain the model.
- If there is evidence of underfitting, consider adding or engineering
features.
- Evaluate the models.
- Create confusion matrices.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Regression:
Predict the continuous valued target feature.
- Understand the schema and field descriptions.
- Identify rows that don't make sense. How many are there and what do they
contain?
- Identify rows without a target value. How many are there and what do they
contain?
- Develop an understanding of the data and determine how to handle missing
values. This should make sense in the business context.
- Identify any potential sources of group leakage. Aggregate where appropriate
to prevent this.
- Visualize target feature.
- Split data into training, validation, and test sets.
- Handle missing data. Prefer to keep data instead of dropping it when
possible.
- Before applying encoders, check if the dataset already contains pre-encoded
features and prefer existing numerical representations.
- Transform ordinal data with an ordinal encoder.
- Transform nominal data with a one hot encoder. Restrict high cardinality
categorical features to a tractable size.
- Standardize numerical features.
- Train multiple models.
- Visualize the actual vs predicted values on training and validation data.
- If there is evidence of overfitting, regularize and retrain the model.
- If there is evidence of underfitting, consider adding or engineering
features.
- Evaluate the model error.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Comparing ML Models:
Evaluate and compare multiple models to determine which is most suitable for
production based on predictive power, robustness, and viability.
- Understand the schema and align metrics with business goals (e.g., cost of
false positives vs. false negatives).
- Establish baselines: define a naive baseline (majority class/mean) and a
simple ML baseline (e.g., Logistic/Linear Regression).
- Ensure rigorous validation: use identical, fixed data splits for all models
and perform $k$-fold cross-validation.
- If data is temporal, use chronological splits for validation.
- Select and report metrics beyond accuracy (e.g., F1-Score, PR-AUC, MAE,
RMSE) that reflect business impact.
- Use bootstrapping to calculate 95% confidence intervals for key metrics to
determine statistical significance.
- Perform slice-based error analysis: evaluate model performance across key
subpopulations and demographics to identify bias or specific failure modes.
- Inspect and compare confusion matrices, residual plots, and calibration
curves.
- Evaluate operational trade-offs: consider inference latency, training time,
compute cost, and model size.
- Assess interpretability using tools like SHAP or LIME where transparency is
required.
- Conclusion: Recommend the optimal model for the specific use case,
justifying the choice with both performance and production viability.
No match:
- Understand the schema and field descriptions.
- Identify rows that don't make sense. How many are there and what do they
contain?
- Identify rows without a target value. How many are there and what do they
contain?
- Drop rows that don't match the schema or don't have the target value (if it
is reasonable to do so).
- Create features to represent when data are missing, if this is meaningful.
- Handle missing data. Prefer to keep data instead of dropping it when
possible.
- Before applying encoders, check if the dataset already contains pre-encoded
features and prefer existing numerical representations.
- Transform ordinal data with an ordinal encoder.
- Transform nominal data with a one hot encoder.
- Standardize numerical features.
- Conclusion: comprehensively answer the prompt in a final markdown cell.
Essential ML Practices
[!IMPORTANT] ALWAYS follow these ML practices
Strict Featurization Ordering: For supervised learning ALWAYS split
the dataset into training and test data BEFORE fitting preprocessing
pipelines (e.g. scaling, encoding). Fit the pipelines on the training data
and test data independently.
Handling Missing or NULL Values: ALWAYS check for and handle missing
and NULL values. First, analyze their frequency. Then, decide whether to
keep them, drop them or impute them with a contextually appropriate value,
and explain your reasoning.
1---2name: ml-best-practices3description: CRITICAL RULE: You MUST use this skill whenever the task involves any machine learning tasks or data analysis. Use this skill if the user's prompt or requirements mention any of the following: * Clustering * Classification * Regression * Time series forecasting * Statistical testing * Model comparison * ML * Data analysis SQL/BigQuery ML HANDOFF: If the user requires a SQL solution, use this skill to dictate the ANALYSIS STEPS (e.g., markdown analysis cells, visualization logic), but defer to `bigquery` for all SQL syntax.4license: Apache-2.05---67# ML Best Practices89I want to read a story about the data, not just run code. Ensure every code cell10is followed by a markdown cell analyzing the results. End the notebook with a11summary comprehensively answering the prompt.1213If there is a good match between the user's request and a corresponding example14plan, then adapt the example plan to fully answer the user's request:1516## Clustering:1718Identify distinct groups based on their features.1920- Understand the schema and field descriptions.21- Visualize features referenced in the prompt (e.g., with histograms,22 scatterplots).23- Transform dates into timestamps.24- Before applying encoders, check if the dataset already contains pre-encoded25 features and prefer existing numerical representations.26- Prefer to keep data instead of dropping it when possible.27- Transform ordinal data with an ordinal encoder.28- Transform nominal data with a one hot encoder.29- Standardize numerical features.30- Perform clustering with a range of values, and collect the silhouette score.31- Choose the optimal number of clusters based on the silhouette score.32- Use dimensionality reduction (e.g., PCA) to project the data into two33 dimensions.34- Scatterplot the samples in two dimensions with cluster labels as the hue.35- Scatterplot the samples in two dimensions with a discrete feature as the36 hue.37- Describe the clusters in text by feature distributions or typical feature38 values.39- Conclusion: comprehensively answer the prompt in a final markdown cell.4041## Time Series Forecasting:4243Develop a predictive model to estimate future values based on historical trends.44How might different modeling approaches impact the prediction accuracy?4546- Understand the schema and field descriptions.47- Visualize the target feature over time at a reasonable granularity.48- Always perform a chronological split on the data to create training,49 validation, and test sets.50- Are there seasonal trends?51- Test for stationarity.52- Discuss possible modeling approaches. How might different modeling53 approaches impact the prediction accuracy?54- Train two time series forecasting models to predict the target feature. Use55 previous seasonality and stationarity information as model hyperparameters.56- Predict the target feature for the training and validation sets.57- Optionally, hypertune models with the validation set.58- Visualize the actual and predicted target feature vs time for each model on59 the training and validation sets.60- Evaluate the validation performance with error metrics.61- Select a model.62- Retrain the selected model on the test and validation sets.63- Predict the test values with the selected model.64- Visualize the average target feature and the predicted test values.65- Conclusion: comprehensively answer the prompt in a final markdown cell.6667## Exploratory Data Analysis / Anomaly Detection:6869Identify and describe any outliers, unusual patterns, or significant trends70observed in the data. Provide visualizations to support your findings.7172- Understand the schema and field descriptions.73- Visualize the target feature distribution in a way that shows outliers.74- Identify and describe any outliers in the target feature.75- Visualize relationships between the target feature and other features.76- Identify and describe unusual patterns or significant trends.77- Visualize patterns and trends.78- Conclusion: comprehensively answer the prompt in a final markdown cell.7980## Classification:8182Given the data, can we classify by the target feature?8384- Understand the schema and field descriptions.85- Identify rows that don't make sense. How many are there and what do they86 contain?87- Identify rows without a target value. How many are there and what do they88 contain?89- Drop rows that don't match the schema or don't have the target value (if it90 is reasonable to do so).91- Split data into training, validation, and test sets.92- Create features to represent when data are missing, if this is meaningful.93- Handle missing data. Prefer to keep data instead of dropping it when94 possible.95- Before applying encoders, check if the dataset already contains pre-encoded96 features and prefer existing numerical representations.97- Transform ordinal data with an ordinal encoder.98- Transform nominal data with a one hot encoder.99- Standardize numerical features.100- Train multiple models.101- If there is evidence of overfitting, regularize and retrain the model.102- If there is evidence of underfitting, consider adding or engineering103 features.104- Evaluate the models.105- Create confusion matrices.106- Conclusion: comprehensively answer the prompt in a final markdown cell.107108## Regression:109110Predict the continuous valued target feature.111112- Understand the schema and field descriptions.113- Identify rows that don't make sense. How many are there and what do they114 contain?115- Identify rows without a target value. How many are there and what do they116 contain?117- Develop an understanding of the data and determine how to handle missing118 values. This should make sense in the business context.119- Identify any potential sources of group leakage. Aggregate where appropriate120 to prevent this.121- Visualize target feature.122- Split data into training, validation, and test sets.123- Handle missing data. Prefer to keep data instead of dropping it when124 possible.125- Before applying encoders, check if the dataset already contains pre-encoded126 features and prefer existing numerical representations.127- Transform ordinal data with an ordinal encoder.128- Transform nominal data with a one hot encoder. Restrict high cardinality129 categorical features to a tractable size.130- Standardize numerical features.131- Train multiple models.132- Visualize the actual vs predicted values on training and validation data.133- If there is evidence of overfitting, regularize and retrain the model.134- If there is evidence of underfitting, consider adding or engineering135 features.136- Evaluate the model error.137- Conclusion: comprehensively answer the prompt in a final markdown cell.138139## Comparing ML Models:140141Evaluate and compare multiple models to determine which is most suitable for142production based on predictive power, robustness, and viability.143144- Understand the schema and align metrics with business goals (e.g., cost of145 false positives vs. false negatives).146- Establish baselines: define a naive baseline (majority class/mean) and a147 simple ML baseline (e.g., Logistic/Linear Regression).148- Ensure rigorous validation: use identical, fixed data splits for all models149 and perform $k$-fold cross-validation.150- If data is temporal, use chronological splits for validation.151- Select and report metrics beyond accuracy (e.g., F1-Score, PR-AUC, MAE,152 RMSE) that reflect business impact.153- Use bootstrapping to calculate 95% confidence intervals for key metrics to154 determine statistical significance.155- Perform slice-based error analysis: evaluate model performance across key156 subpopulations and demographics to identify bias or specific failure modes.157- Inspect and compare confusion matrices, residual plots, and calibration158 curves.159- Evaluate operational trade-offs: consider inference latency, training time,160 compute cost, and model size.161- Assess interpretability using tools like SHAP or LIME where transparency is162 required.163- Conclusion: Recommend the optimal model for the specific use case,164 justifying the choice with both performance and production viability.165166## No match:167168- Understand the schema and field descriptions.169- Identify rows that don't make sense. How many are there and what do they170 contain?171- Identify rows without a target value. How many are there and what do they172 contain?173- Drop rows that don't match the schema or don't have the target value (if it174 is reasonable to do so).175- Create features to represent when data are missing, if this is meaningful.176- Handle missing data. Prefer to keep data instead of dropping it when177 possible.178- Before applying encoders, check if the dataset already contains pre-encoded179 features and prefer existing numerical representations.180- Transform ordinal data with an ordinal encoder.181- Transform nominal data with a one hot encoder.182- Standardize numerical features.183- Conclusion: comprehensively answer the prompt in a final markdown cell.184185## Essential ML Practices186187[!IMPORTANT] ALWAYS follow these ML practices188189- **Strict Featurization Ordering**: For supervised learning **ALWAYS** split190 the dataset into training and test data **BEFORE** fitting preprocessing191 pipelines (e.g. scaling, encoding). Fit the pipelines on the training data192 and test data independently.193194- **Handling Missing or NULL Values**: **ALWAYS** check for and handle missing195 and NULL values. First, analyze their frequency. Then, decide whether to196 keep them, drop them or impute them with a contextually appropriate value,197 and explain your reasoning.