🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

BigQuery ML: Model Types, Training & Prediction

GCP Data EngineeringBigQuery MLđŸŸĸ Free Lesson

BigQuery ML Deep Dive

Master BigQuery ML including model types, training, prediction, feature engineering, and integration with Vertex AI.

18 min readAdvanced

What You'll Learn

  • 1Map a business question onto the correct BigQuery ML model type
  • 2Write CREATE MODEL, ML.EVALUATE and ML.PREDICT statements with the right options
  • 3Read precision, recall and ROC AUC off a confusion matrix without a notebook
  • 4Decide when a workload belongs in BigQuery ML and when it belongs in Vertex AI

Why the Export Step Disappears

Most tabular ML projects fail on plumbing rather than on algorithms. A copy of the production table lands in a bucket, a notebook pulls it into pandas, a model is trained over last Tuesday's snapshot, and predictions are pushed back by hand. Every hop adds a place where the training set drifts from the live schema, and the copy itself costs storage and egress. BigQuery ML collapses that loop into SQL: CREATE MODEL reads a SELECT statement, trains inside the analytical engine that already stores the data, and writes the model back as a logical table you query with ML.PREDICT. Nothing leaves the project, so row level permissions on the source table apply during training, and the feature columns you project are exactly what the scoring query sees.

The sweet spot is supervised learning over structured data: churn scoring, lead ranking, demand forecasting, anomaly flagging. Because training is a query, it scales with the same slot system as your dashboards, and a model over a 500 million row table needs no cluster provisioned in advance. Training bills on the data processed rather than on idle machine time, so an experiment that scans 40 GB costs cents instead of an always-on notebook instance.

The boundary matters as much as the feature. BigQuery ML is not a deep learning platform: there is no custom training loop, no arbitrary Python, and no way to feed raw images or text beyond embeddings computed elsewhere. Models that need GPU training, a custom loss function, or a serving stack outside BigQuery belong in Vertex AI. A workable rule: if the training set is a SELECT statement and the model matches a supported type, stay in BigQuery ML; if you need a framework, move.

Choosing the Model Type

Twelve native model families are available, and picking the wrong one is the most common design error in interviews and in production. Start with the simplest model that can express the relationship, then escalate only when the evaluation metrics justify it.

Model typeQuestion it answersKey metricWhen to reach for it
LINEAR_REGHow much?R-squared, MAEEffect must be explained to a stakeholder
LOGISTIC_REGWill it happen?ROC AUC, F1Binary outcome, needs probabilities and coefficients
BOOSTED_TREE_CLASSIFIERWill it happen, non-linearly?ROC AUC, F1Interactions and thresholds matter more than interpretability
RANDOM_FOREST_REGRESSORHow much, non-linearly?RMSERobust baseline with little tuning
XGBOOST_*Either, with tight controlROC AUC, RMSEYou want histogram tree method and per-feature control
KMEANSWho is alike?Silhouette scoreSegmentation before any labelled target exists
MATRIX_FACTORIZATIONWhat will they like?RMSERecommendations from an interaction matrix
ARIMA_PLUSWhat happens next period?Root mean squared errorOne forecast per series, seasonality and holidays included
DNN_CLASSIFIER / WIDE_AND_DEEPEither, with capacityROC AUCLarge datasets where trees plateau
TENSORFLOW / ONNXAnythingModel suppliedYou trained elsewhere and only want SQL scoring

LOGISTIC_REG is the right first answer for a churn problem: it returns predicted_<label> together with a probability struct, it exposes coefficients you can rank, and it trains in a single query. Boosted trees usually buy two to four points of ROC AUC on the same features but hide the decision boundary, so treat the lift as a business question before accepting the trade. For forecasting, ARIMA_PLUS performs automatic ARIMA order selection, detects trend and seasonality, models missing values, and can include holiday effects through the holiday_region option, which is why a single statement can replace a hand-built seasonal decomposition.

Training Without a Notebook

Training is one statement with options in the OPTIONS clause. The label column is named, the split is declared, and hyperparameter search runs inside the engine.

-- Classification model for churn prediction
CREATE OR REPLACE MODEL `project.dataset.churn_model`
OPTIONS(
  model_type='BOOSTED_TREE_CLASSIFIER',
  input_label_cols=['churned'],
  data_split_method='RANDOM',
  data_split_test_fraction=0.2,
  num_trials=20,
  max_parallel_trials=4,
  max_tree_depth=8,
  learn_rate=0.1,
  early_stop=TRUE,
  min_split_loss=0.01
) AS
SELECT
  user_id,
  tenure_months,
  monthly_charges,
  total_charges,
  contract_type,
  payment_method,
  churned
FROM `project.dataset.user_features`
WHERE split = 'train';

Three options do most of the work. data_split_method accepts RANDOM, SEQUENTIAL, CUSTOM and AUTO_SPLIT, so a time ordered table must use SEQUENTIAL or a CUSTOM split column, otherwise future rows leak into training and the reported accuracy is fiction. early_stop=TRUE halts a trial once validation loss stops improving by min_rel_progress, which caps wasted iterations when num_trials is large. num_trials turns training into a search: each trial is an independent fit, so cost and wall time grow roughly linearly with the count and 20 trials is already a serious budget. ML.TRAINING_INFO returns one row per trial with its iteration count and loss curve, which is how you confirm the search did what you think it did.

Reading the Evaluation Output

ML.EVALUATE returns one row of metrics, but the numbers only become useful when you can reconstruct them.

SELECT *
FROM ML.EVALUATE(MODEL `project.dataset.churn_model`,
  (SELECT * FROM `project.dataset.user_features` WHERE split = 'test'));

SELECT *
FROM ML.CONFUSION_MATRIX(MODEL `project.dataset.churn_model`,
  (SELECT * FROM `project.dataset.user_features` WHERE split = 'test'));

SELECT *
FROM ML.ROC_CURVE(MODEL `project.dataset.churn_model`,
  (SELECT * FROM `project.dataset.user_features` WHERE split = 'test'))
ORDER BY threshold;

Suppose the confusion matrix reports 420 true positives, 80 false positives, 60 false negatives and 440 true negatives over 1,000 rows. Accuracy is 860 divided by 1,000, so 86 percent. Precision is 420 over 500 predicted churners, or 84 percent: of the customers the model would email, four in five really leave. Recall is 420 over 480 actual churners, 87.5 percent: the campaign catches seven in eight leavers and misses 60. The F1 score is the harmonic mean, 2 times 0.84 times 0.875 divided by their sum, giving 85.7 percent. ML.ROC_CURVE adds the full threshold sweep with area_under_roc, and the practical move is to pick the threshold from cost rather than from accuracy: a retention offer worth 20 dollars against a customer worth 200 justifies a lower threshold and more false positives.

Prediction and Serving

Scoring reuses the same engine as training, which is what makes deployment a SQL change rather than a service deployment.

-- Batch prediction into an auditable table
CREATE OR REPLACE TABLE `project.dataset.churn_predictions` AS
SELECT
  user_id,
  predicted_churned,
  predicted_churned_probs
FROM ML.PREDICT(MODEL `project.dataset.churn_model`,
  (SELECT * FROM `project.dataset.user_features` WHERE split = 'score'));

-- Point prediction for a single record
SELECT *
FROM ML.PREDICT(MODEL `project.dataset.churn_model`,
  (SELECT
    'user_123' AS user_id,
    24 AS tenure_months,
    65.50 AS monthly_charges,
    1572.00 AS total_charges,
    'Two year' AS contract_type,
    'Credit card' AS payment_method));

-- Top five drivers behind each prediction
SELECT *
FROM ML.EXPLAIN_PREDICT(MODEL `project.dataset.churn_model`,
  (SELECT * FROM `project.dataset.user_features` WHERE split = 'score'),
  TOP_K_FEATURES => 5);

Batch scoring writes a table you can join to a campaign list, while an application that needs a score at request time calls ML.PREDICT through the BigQuery API over a single row and pays for a query, not for a replica. ML.EXPLAIN_PREDICT returns per-row feature attributions, which is what a support agent needs when a customer asks why the offer appeared. The prediction output keeps the model contract honest: every column of the training select must be present at scoring time, and a renamed or missing column fails the statement rather than silently scoring nulls.

Feature Engineering Inside the Model

The TRANSFORM clause runs the same preprocessing at training and at prediction, which removes the classic mismatch where a notebook scales features and the service does not.

CREATE OR REPLACE MODEL `project.dataset.churn_model_v2`
TRANSFORM(
  SAFE_DIVIDE(total_charges, NULLIF(tenure_months, 0)) AS avg_monthly_value,
  LOG1P(monthly_charges) AS log_charges,
  ML.FEATURE_CROSS(STRUCT(contract_type, payment_method)) AS contract_pay
)
OPTIONS(
  model_type='LOGISTIC_REG',
  input_label_cols=['churned'],
  auto_class_weights=TRUE
) AS
SELECT tenure_months, monthly_charges, total_charges, contract_type, payment_method, churned
FROM `project.dataset.user_features`
WHERE split = 'train';

Because the expressions live in the model artefact, ML.PREDICT applies them automatically and a caller may not even know they exist. auto_class_weights=TRUE rebalances a skewed label so a 4 percent churn rate does not collapse into a model that predicts "stay" for everyone. When the transform turns out to be wrong, ML.EVALUATE on the same test set tells you immediately, because the split and the preprocessing move together.

Cost, Limits and the Vertex AI Boundary

On-demand queries are billed at 5 dollars per TiB scanned, so a training run over 40 GB costs about 20 cents per trial and 20 trials costs roughly four dollars. Model tables consume storage at the standard BigQuery rate of 2 cents per GB-month, and INFORMATION_SCHEMA.MODELS shows how much space each model occupies. The practical ceilings show up elsewhere: prediction over a huge table scans that table, hyperparameter searches multiply the training bill, and very wide feature sets inflate both memory and cost.

SituationStay in BigQuery MLMove to Vertex AI
Labelled table, one of the native typesYes, single statementNo
Custom PyTorch or TensorFlow training loopNoYes, bring your own container
Text or image model needing a preprocessorNoYes, or precompute embeddings first
Low latency online endpoint with traffic splittingLimited, API query per scoreYes, managed endpoint with canary
Feature reuse across several modelsTRANSFORM clauseVertex AI Feature Store
Explainability for a business reviewerML.EXPLAIN_PREDICTExplainable AI with attribution plots

For teams already standardising on Vertex AI, a BigQuery ML model can be exported to the Vertex AI model registry and served from an endpoint, so starting in SQL does not paint you into a corner. The honest interview answer is that BigQuery ML covers roughly eighty percent of tabular workloads at a fraction of the operational cost, and the remaining twenty percent needs the flexibility of the managed ML platform.

✨

Best Practice: Start with LOGISTIC_REG or LINEAR_REG as a baseline and only accept a boosted tree when ML.EVALUATE shows a real lift on the holdout split. Set data_split_method deliberately for time ordered data, cap num_trials because every trial is a full training run, and keep preprocessing inside TRANSFORM so training and scoring can never disagree.

Common Interview Questions

Q1: What is BigQuery ML?

Answer: BigQuery ML lets you build and deploy machine learning models with SQL directly inside BigQuery. It supports classification, regression, clustering, time series and recommendation models without exporting data or writing Python, and the model itself is stored as a logical table you query with ML.PREDICT.

Q2: When would you use BigQuery ML instead of Vertex AI?

Answer: Use BigQuery ML when the training set is a SQL query and the model fits one of the native types, because there is no pipeline to maintain. Reach for Vertex AI when you need a custom framework, GPU training, a pre-built online endpoint with traffic splitting, or a feature store shared across models.

Q3: How do you improve a BigQuery ML model?

Answer: Engineer features such as ratios and crosses, usually through the TRANSFORM clause, raise num_trials only while validation loss is still falling, collect more history, drop features that ML.FEATURE_IMPORTANCE ranks near zero, and move from a linear model to boosted trees once the simple baseline is honest. early_stop prevents the extra iterations from overfitting.

Q4: What do time series models give you that a forecast query does not?

Answer: ARIMA_PLUS performs automatic order selection, separates trend from seasonality, imputes missing points, and can model holiday regressors with holiday_region. ML.FORECAST then returns the horizon with confidence intervals, and ML.ARIMA_OPTIMIZE refreshes the parameters as new history arrives.

Q5: How do you serve BigQuery ML predictions in production?

Answer: Batch workloads use ML.PREDICT writing to a table on a scheduler, usually from Cloud Composer. Interactive products call the BigQuery API with a single row and read predicted_<label> plus the probability struct. Traffic that needs sub second latency or A/B splits can be exported to a Vertex AI endpoint.

Interview Questions

Q1: Which options must you set for a time ordered dataset?

Set data_split_method to SEQUENTIAL or supply a CUSTOM split column so the holdout set is genuinely later than the training set; the default random split leaks future rows and inflates the metrics.

Q2: What do ML.FEATURE_IMPORTANCE and ML.EXPLAIN_PREDICT each return?

ML.FEATURE_IMPORTANCE returns one global importance row per feature for tree models, while ML.EXPLAIN_PREDICT returns per-row attributions for a specific prediction, which is what a support agent needs to justify an offer.

Q3: How does auto_class_weights change training?

It rebalances the label distribution during training so a rare class, such as 4 percent churn, is not drowned out by the majority class, which lifts recall at the cost of more false positives.

Q4: Where does the TRANSFORM clause execute?

Inside the model artefact: the same expressions run during CREATE MODEL and again on every ML.PREDICT call, so callers never have to reproduce preprocessing in application code.

Common Mistakes

Letting BigQuery randomly split a time ordered table

Fix: Use data_split_method='SEQUENTIAL' or a CUSTOM split column so the test set is truly in the future.

Reaching for boosted trees before a linear baseline exists

Fix: Train LOGISTIC_REG first; only accept the tree when ML.EVALUATE shows a lift worth losing interpretability for.

Rebuilding preprocessing in the scoring query

Fix: Move expressions into the TRANSFORM clause so training and ML.PREDICT share one definition.

Key Takeaways

  • CREATE MODEL runs inside BigQuery, so no data export, no egress and the same IAM rules apply to training as to querying
  • Each num_trials entry is a separate fit, which multiplies training cost, so early_stop and min_rel_progress are budget controls as much as accuracy controls
  • Precision and recall come straight from ML.CONFUSION_MATRIX: 420, 80, 60, 440 gives 84 percent precision and 87.5 percent recall
  • The TRANSFORM clause guarantees identical preprocessing at training and prediction, and ML.EXPLAIN_PREDICT returns per-row feature attributions for the same model
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement