This tutorial shows you how to import an Open Neural Network Exchange (ONNX) model that's trained with scikit-learn. You import the model into a BigQuery dataset and use it to make predictions using a SQL query.
ONNX provides a uniform format that is designed to represent any machine learning (ML) framework. BigQuery ML support for ONNX lets you do the following:
CREATE MODEL statement to import the ONNX model into
BigQuery.ML.PREDICT function to make predictions with the imported
ONNX model.In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Verify that billing is enabled for your Google Cloud project.
Enable the BigQuery and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
If you create a new project, you're the project owner, and you're granted all of the required Identity and Access Management (IAM) permissions that you need to complete this tutorial.
If you're using an existing project, do the following.
Make sure that you have the following role or roles on the project:
roles/bigquery.studioAdmin)roles/storage.objectCreator)In the Google Cloud console, go to the IAM page.
Go to IAMIn the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.
In the Google Cloud console, go to the IAM page.
Go to IAMIn the New principals field, enter your user identifier. This is typically the email address for a Google Account.
For more information about IAM permissions in BigQuery, see IAM permissions.
The following code samples show you how to train a classification model with
scikit-learn and how to convert the resulting pipeline into ONNX format. This
tutorial uses a prebuilt example model that's stored at
gs://cloud-samples-data/bigquery/ml/onnx/pipeline_rf.onnx. You don't have to
complete these steps if you're using the sample model.
Use the following sample code to create and train a scikit-learn pipeline on the Iris dataset. For instructions about installing and using scikit-learn, see the scikit-learn installation guide.
import numpy
from sklearn.datasets import load_iris
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
data = load_iris()
X = data.data[:, :4]
y = data.target
ind = numpy.arange(X.shape[0])
numpy.random.shuffle(ind)
X = X[ind, :].copy()
y = y[ind].copy()
pipe = Pipeline([('scaler', StandardScaler()),
('clr', RandomForestClassifier())])
pipe.fit(X, y)
Use the following sample code in sklearn-onnx to convert the scikit-learn
pipeline into an ONNX model that's named pipeline_rf.onnx.
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
# Disable zipmap as it is not supported in BigQuery ML.
options = {id(pipe): {'zipmap': False}}
# Define input features. scikit-learn does not store information about the
# training dataset. It is not always possible to retrieve the number of features
# or their types. That's why the function needs another argument called initial_types.
initial_types = [
('sepal_length', FloatTensorType([None, 1])),
('sepal_width', FloatTensorType([None, 1])),
('petal_length', FloatTensorType([None, 1])),
('petal_width', FloatTensorType([None, 1])),
]
# Convert the model.
model_onnx = convert_sklearn(
pipe, 'pipeline_rf', initial_types=initial_types, options=options
)
# And save.
with open('pipeline_rf.onnx', 'wb') as f:
f.write(model_onnx.SerializeToString())
After you save your model, do the following:
In the Google Cloud console, go to the BigQuery page.
In the Explorer pane, click your project name.
Click View actions > Create dataset
On the Create dataset page, do the following:
For Dataset ID, enter bqml_tutorial.
For Location type, select Multi-region, and then select US.
Leave the remaining default settings as they are, and click Create dataset.
To create a new dataset, use the
bq mk --dataset command.
Create a dataset named bqml_tutorial with the data location set to US.
bq mk --dataset \ --location=US \ --description "BigQuery ML tutorial dataset." \ bqml_tutorial
Confirm that the dataset was created:
bq lsCall the datasets.insert
method with a defined dataset resource.
{ "datasetReference": { "datasetId": "bqml_tutorial" } }
Before trying this sample, follow the BigQuery DataFrames setup instructions in the BigQuery quickstart using BigQuery DataFrames. For more information, see the BigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up ADC for a local development environment.
The following steps show you how to import the sample ONNX model from
Cloud Storage by using a CREATE MODEL statement.
To import the ONNX model into your dataset, select one of the following options:
In the Google Cloud console, go to the BigQuery Studio page.
In the query editor, enter the following CREATE MODEL statement.
CREATE OR REPLACE MODEL `bqml_tutorial.imported_onnx_model` OPTIONS (MODEL_TYPE='ONNX', MODEL_PATH='BUCKET_PATH')
Replace BUCKET_PATH with the path to the model
that you uploaded to Cloud Storage. If you're using the sample model,
replace BUCKET_PATH with the following value:
gs://cloud-samples-data/bigquery/ml/onnx/pipeline_rf.onnx.
When the operation is complete, you see a message similar to the
following: Successfully created model named imported_onnx_model.
Your new model appears in the Resources panel. Models are
indicated by the model icon:
If you select the new model in the Resources panel, information
about the model appears adjacent to the Query editor.
Import the ONNX model from Cloud Storage by entering the
following CREATE MODEL statement.
bq query --use_legacy_sql=false \ "CREATE OR REPLACE MODEL `bqml_tutorial.imported_onnx_model` OPTIONS (MODEL_TYPE='ONNX', MODEL_PATH='BUCKET_PATH')"
Replace BUCKET_PATH with the path to the model
that you uploaded to Cloud Storage. If you're using the sample model,
replace BUCKET_PATH with the following value:
gs://cloud-samples-data/bigquery/ml/onnx/pipeline_rf.onnx.
When the operation is complete, you see a message similar to the
following: Successfully created model named imported_onnx_model.
After you import the model, verify that the model appears in the dataset.
bq ls -m bqml_tutorial
The output is similar to the following:
tableId Type --------------------- ------- imported_onnx_model MODEL
Before trying this sample, follow the BigQuery DataFrames setup instructions in the BigQuery quickstart using BigQuery DataFrames. For more information, see the BigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up ADC for a local development environment.
Import the model by using the ONNXModel object.
For more information about importing ONNX models into BigQuery,
including format and storage requirements, see The CREATE MODEL statement for
importing ONNX models.
After importing the ONNX model, you use the ML.PREDICT function to make
predictions with the model.
The query in the following steps uses imported_onnx_model to make predictions
using input data from the iris table in the ml_datasets public dataset. The
ONNX model expects four FLOAT values as input:
sepal_lengthsepal_widthpetal_lengthpetal_widthThese inputs match the initial_types that were defined when you converted the
model into ONNX format.
The outputs include the label and probabilities columns, and the columns
from the input table. label represents the predicted class label.
probabilities is an array of probabilities representing probabilities for
each class.
To make predictions with the imported ONNX model, choose one of the following options:
Go to the BigQuery Studio page.
In the query editor, enter this query that uses the ML.PREDICT
function.
SELECT * FROM ML.PREDICT(MODEL `bqml_tutorial.imported_onnx_model`, ( SELECT * FROM `bigquery-public-data.ml_datasets.iris` ) )
The query results are similar to the following:
Run the query that uses ML.PREDICT.
bq query --use_legacy_sql=false \ 'SELECT * FROM ML.PREDICT( MODEL `example_dataset.imported_onnx_model`, (SELECT * FROM `bigquery-public-data.ml_datasets.iris`))'
Before trying this sample, follow the BigQuery DataFrames setup instructions in the BigQuery quickstart using BigQuery DataFrames. For more information, see the BigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up ADC for a local development environment.
Use the predict function to run the ONNX model.
The result is similar to the following:
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
Alternatively, to remove the individual resources used in this tutorial, do the following:
Optional: Delete the dataset.
CREATE MODEL statement for ONNX models.Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-07-17 UTC.