1.3 Generating Predictions with BigQuery ML
Key Takeaways
ML.PREDICT is the general inference function; forecasting models use ML.FORECAST, matrix factorization uses ML.RECOMMEND, and clustering models use ML.PREDICT for assignment or ML.DETECT_ANOMALIES for outliers.
BigQuery ML inference is inherently batch and serverless — it has no endpoint, no autoscaling, and no single-digit-millisecond path, so real-time serving requires exporting the model or registering it with Agent Platform.
ML.EXPLAIN_PREDICT returns per-row feature attributions alongside each prediction, and top_k_features controls how many contributors are returned.
EXPORT MODEL writes a TensorFlow SavedModel or XGBoost Booster to Cloud Storage, which can then be deployed to an Agent Platform Inference endpoint for online serving.
A remote model registered against an Agent Platform endpoint lets ML.PREDICT call a model trained outside BigQuery, keeping the SQL interface while the model lives elsewhere.
1.3 Generating Predictions with BigQuery ML
Blueprint reference: Section 1.1, "Generating predictions using BigQuery ML."
Training a model in SQL is the easy half. The exam concentrates on the consequences of BigQuery ML's serving model, because that is where architectural decisions actually get made: BigQuery ML inference is serverless, analytical, and batch-shaped. There is no endpoint to deploy, no minimum replica count, and no path to a 20 ms p99. Every scenario that mentions real-time inference is testing whether you know to leave BigQuery for the serving step.
The Inference Function Family
| Function | Applies to | Returns |
|---|---|---|
ML.PREDICT | Regression, classification, clustering, imported models | predicted_<label> plus, for classifiers, a predicted_<label>_probs array |
ML.FORECAST | ARIMA_PLUS, ARIMA_PLUS_XREG | Forecast values with prediction intervals and confidence levels |
ML.RECOMMEND | MATRIX_FACTORIZATION | Ranked item recommendations per user |
ML.DETECT_ANOMALIES | KMEANS, ARIMA_PLUS, AUTOENCODER, PCA | Boolean is_anomaly plus a distance or reconstruction score |
ML.EXPLAIN_PREDICT | Supervised models | Predictions plus per-row feature attributions |
ML.GENERATE_EMBEDDING | Embedding and remote embedding models | Dense vector representations |
AI.GENERATE, AI.GENERATE_TABLE | Remote Gemini models | Generated text or a typed table |
The single most common exam slip is reaching for ML.PREDICT on a time-series model. ARIMA_PLUS models forecast forward from the training horizon; they do not score arbitrary input rows, so ML.FORECAST with a horizon and confidence_level is the only correct call.
SELECT * FROM ML.FORECAST(
MODEL `analytics.daily_demand`,
STRUCT(30 AS horizon, 0.95 AS confidence_level)
);
Classification Output Shape
A binary classifier does not return only a class. It returns the predicted label plus an array of (label, prob) structs, which you must unnest to threshold on probability rather than accepting the default 0.5 cut.
SELECT
customer_id,
predicted_churned,
(SELECT prob FROM UNNEST(predicted_churned_probs)
WHERE label = TRUE) AS churn_probability
FROM ML.PREDICT(MODEL `analytics.churn_model`,
TABLE `analytics.active_customers`)
WHERE (SELECT prob FROM UNNEST(predicted_churned_probs)
WHERE label = TRUE) > 0.72;
This matters commercially. If a retention offer costs money, the operating threshold is a business decision, not a modelling default. ML.ROC_CURVE gives you the true-positive and false-positive rates at each threshold so you can pick the point that maximizes expected value.
Per-Row Explanations
ML.EXPLAIN_PREDICT returns each prediction with the feature attributions that produced it, ordered by absolute contribution. top_k_features bounds the output width.
SELECT * FROM ML.EXPLAIN_PREDICT(
MODEL `analytics.credit_model`,
TABLE `analytics.applications`,
STRUCT(5 AS top_k_features)
);
For linear models the attributions are exact coefficient contributions. For tree and DNN models BigQuery ML uses Shapley values, computed by sampling. ML.GLOBAL_EXPLAIN aggregates the same machinery across the whole training set to answer "which features matter overall," and requires enable_global_explain = TRUE at CREATE MODEL time — a flag you cannot retrofit without retraining.
The adverse-action notice requirement in lending is the canonical scenario: regulators require a per-applicant reason, which is a row-level explanation, so ML.EXPLAIN_PREDICT is correct and ML.GLOBAL_EXPLAIN is not.
When Predictions Must Leave BigQuery
BigQuery ML query latency is measured in seconds. Three patterns move a BigQuery-trained model to a low-latency surface.
1. EXPORT MODEL to Cloud Storage. Linear, logistic, DNN, Wide-and-Deep, k-means, autoencoder, and AutoML Tables models export as a TensorFlow SavedModel. Boosted tree and random forest models export as an XGBoost Booster file. The exported artifact can be uploaded to the Model Registry and deployed to an Agent Platform Inference endpoint, or run in any container that speaks TensorFlow Serving.
EXPORT MODEL `analytics.churn_model`
OPTIONS (URI = 'gs://my-models/churn/v3');
2. Register a remote model. The inverse direction: create a BigQuery model object that points at an already-deployed Agent Platform endpoint through a BigQuery connection. Analysts keep writing ML.PREDICT while inference executes on the endpoint, which means one model version serves both the warehouse and the application.
3. Scheduled batch materialization. For recommendations, propensity scores, and lead ranking, real-time inference is often unnecessary. A scheduled query writes scores to a serving table, and the application reads that table — or an exported copy in Bigtable or Firestore — with millisecond latency. This is the most cost-effective answer whenever the scenario tolerates hours-old scores.
Cost and Performance Notes
ML.PREDICTis billed as a normal BigQuery query on the bytes scanned. Predicting onSELECT *over a wide table is expensive; select only the model's input columns.- Partition and cluster the input table on the columns used in the
WHEREclause; inference over a partition-pruned scan can be an order of magnitude cheaper. - Batch inference over very large tables benefits from writing results to a destination table rather than streaming them to the client.
ML.PREDICTon an imported TensorFlow model runs the model inside BigQuery slots and has model size limits, so very large deep models belong on an endpoint rather than imported.
Exam Traps
- Real-time serving from BigQuery ML. If the scenario says "under 100 ms" or "per user request," the answer involves exporting or registering with Agent Platform Inference, not a scheduled query.
ML.PREDICTonARIMA_PLUS. UseML.FORECAST.- Assuming
ML.GLOBAL_EXPLAINworks retroactively. It requires the flag at creation time. - Forgetting the probability array.
predicted_<label>already applied a 0.5 threshold; business thresholds require unnesting the probabilities.
A demand-planning team trained an ARIMA_PLUS model in BigQuery ML on three years of daily sales. They now need the next 30 days of predicted demand with 95% prediction intervals. Which call produces this?
ML.FORECAST with STRUCT(30 AS horizon, 0.95 AS confidence_level).
ML.EVALUATE with a holdout table containing the next 30 days of actuals.
ML.DETECT_ANOMALIES with a 0.95 anomaly_prob_threshold to identify the 30 most likely future values.
ML.PREDICT with the next 30 dates supplied as input rows and a confidence_level struct option.
A lending platform trains a boosted tree model in BigQuery ML. Regulation requires that every declined applicant receive the specific factors that drove their individual decision. What must the team implement?
ML.GLOBAL_EXPLAIN over the training set, publishing the ranked feature list in the terms and conditions.
ML.FEATURE_IMPORTANCE, mapping the top three gain-ranked features into the decline letter template.
ML.EXPLAIN_PREDICT with a top_k_features option, returning per-applicant attributions with each score.
ML.WEIGHTS, converting each coefficient into a plain-language reason code.
A BigQuery ML logistic regression scores well and now must serve a mobile checkout flow with a p99 latency budget of 80 milliseconds per request. Which architecture meets the requirement with the least rework?
Increase the BigQuery reservation slot count so ML.PREDICT queries complete within the latency budget.
Create a materialized view over ML.PREDICT so BigQuery maintains the predictions incrementally and the backend queries the view.
Schedule ML.PREDICT to run every five minutes and have the mobile backend read the most recent scores from the results table.
Use EXPORT MODEL to write the TensorFlow SavedModel to Cloud Storage, upload it to the Model Registry, and deploy it to an Agent Platform Inference endpoint that the backend calls.
A marketing team wants to target only customers whose churn probability exceeds 0.8, but their query returns far more rows than expected. Their SQL selects predicted_churned = TRUE from ML.PREDICT. What is the defect?
predicted_churned applies the default 0.5 decision threshold; the 0.8 cut requires unnesting predicted_churned_probs and filtering on the probability.
ML.PREDICT returns calibrated probabilities only when the model was trained with enable_global_explain, which was not set.
The model needs class weights because the boolean prediction column is biased toward the majority class.
predicted_churned is a string rather than a boolean, so the equality comparison matches every non-empty value.
Sections you finish are checked off in the contents.