Make predictions with imported TensorFlow models Stay organized with collections Save and categorize content based on your preferences.
In this tutorial, you import TensorFlow models into aBigQuery ML dataset. Then, you use a SQL query to make predictions fromthe imported models.
Objectives
- Use the
CREATE MODELstatement to import TensorFlow modelsinto BigQuery ML. - Use the
ML.PREDICTfunction to make predictions with the importedTensorFlow models.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage, use thepricing 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, seeClean up.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Ensure that the BigQuery API is enabled.
- Ensure that you have thenecessary permissions to perform the tasks in this document.
Required roles
If you create a new project, you are the project owner, and you are granted allof the required Identity and Access Management (IAM) permissions that you need to completethis tutorial.
If you are using an existing project, theBigQuery Studio Admin (roles/bigquery.studioAdmin) role grants all of thepermissions that are needed to complete this tutorial.
Make sure that you have the following role or roles on the project:BigQuery Studio Admin (roles/bigquery.studioAdmin).
Check for the roles
In the Google Cloud console, go to theIAM page.
Go to IAM- Select the project.
In thePrincipal 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.
- For all rows that specify or include you, check theRole column to see whether the list of roles includes the required roles.
Grant the roles
In the Google Cloud console, go to theIAM page.
Go to IAM- Select the project.
- ClickGrant access.
In theNew principals field, enter your user identifier. This is typically the email address for a Google Account.
- In theSelect a role list, select a role.
- To grant additional roles, clickAdd another role and add each additional role.
- ClickSave.
For more information about IAM permissions in BigQuery,seeBigQuery permissions.
Create a dataset
Create a BigQuery dataset to store your ML model.
Console
In the Google Cloud console, go to theBigQuery page.
In theExplorer pane, click your project name.
ClickView actions > Create dataset
On theCreate dataset page, do the following:
ForDataset ID, enter
bqml_tutorial.ForLocation type, selectMulti-region, and then selectUS (multiple regions in United States).
Leave the remaining default settings as they are, and clickCreate dataset.
bq
To create a new dataset, use thebq mk commandwith the--location flag. For a full list of possible parameters, see thebq mk --dataset commandreference.
Create a dataset named
bqml_tutorialwith the data location set toUSand a description ofBigQuery ML tutorial dataset:bq --location=US mk -d \ --description "BigQuery ML tutorial dataset." \ bqml_tutorial
Instead of using the
--datasetflag, the command uses the-dshortcut.If you omit-dand--dataset, the command defaults to creating adataset.Confirm that the dataset was created:
bqls
API
Call thedatasets.insertmethod with a defineddataset resource.
{"datasetReference":{"datasetId":"bqml_tutorial"}}
BigQuery DataFrames
Before trying this sample, follow the BigQuery DataFrames setup instructions in theBigQuery quickstart using BigQuery DataFrames. For more information, see theBigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up ADC for a local development environment.
importgoogle.cloud.bigquerybqclient=google.cloud.bigquery.Client()bqclient.create_dataset("bqml_tutorial",exists_ok=True)Import a TensorFlow model
The following steps show you how to import a model from Cloud Storage.The path to the model isgs://cloud-training-demos/txtclass/export/exporter/1549825580/*. The importedmodel name isimported_tf_model.
Note the Cloud Storage URI ends in a wildcard character (*).This character indicates that BigQuery ML should import any assetsassociated with the model.
The imported model is a TensorFlow text classifier model thatpredicts which website published a given article title.
To import the TensorFlow model into your dataset, follow thesesteps.
Console
In the Google Cloud console, go to theBigQuery page.
ForCreate new, clickSQL query.
In the query editor, enter this
CREATE MODELstatement, and then clickRun.CREATEORREPLACEMODEL`bqml_tutorial.imported_tf_model`OPTIONS(MODEL_TYPE='TENSORFLOW',MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')
When the operation is complete, you should see a message like
Successfully created model named imported_tf_model.Your new model appears in theResources panel. Models areindicated by the model icon:
.If you select the new model in theResources panel, informationabout the model appears below theQuery editor.

bq
Import the TensorFlow model from Cloud Storageby entering the following
CREATE MODELstatement.bqquery--use_legacy_sql=false\"CREATE OR REPLACE MODEL`bqml_tutorial.imported_tf_model`OPTIONS(MODEL_TYPE='TENSORFLOW',MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')"
After you import the model, verify that the model appears in thedataset.
bq ls -m bqml_tutorial
The output is similar to the following:
tableIdType--------------------------imported_tf_modelMODEL
API
Insert a new job andpopulate thejobs#configuration.queryproperty in the request body.
{"query":"CREATE MODEL `PROJECT_ID:bqml_tutorial.imported_tf_model` OPTIONS(MODEL_TYPE='TENSORFLOW' MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')"}
ReplacePROJECT_ID with the name of yourproject and dataset.
BigQuery DataFrames
Before trying this sample, follow the BigQuery DataFrames setup instructions in theBigQuery quickstart using BigQuery DataFrames. For more information, see theBigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up ADC for a local development environment.
Import the model by using theTensorFlowModel object.
importbigframesfrombigframes.ml.importedimportTensorFlowModelbigframes.options.bigquery.project=PROJECT_ID# You can change the location to one of the valid locations: https://cloud.google.com/bigquery/docs/locations#supported_locationsbigframes.options.bigquery.location="US"imported_tensorflow_model=TensorFlowModel(model_path="gs://cloud-training-demos/txtclass/export/exporter/1549825580/*")For more information about importing TensorFlow models intoBigQuery ML, including format and storage requirements, see theCREATE MODEL statement for importing TensorFlow models.
Make predictions with the imported TensorFlow model
After importing the TensorFlow model, you use theML.PREDICT functionto make predictions with the model.
The following query usesimported_tf_model to make predictions using inputdata from thefull table in the public datasethacker_news. In the query,the TensorFlow model'sserving_input_fn function specifies thatthe model expects a single input string namedinput. The subquery assigns thealiasinput to thetitle column in the subquery'sSELECT statement.
To make predictions with the imported TensorFlow model, followthese steps.
Console
In the Google Cloud console, go to theBigQuery page.
UnderCreate new, clickSQL query.
In the query editor, enter this query that uses the
ML.PREDICTfunction.SELECT*FROMML.PREDICT(MODEL`bqml_tutorial.imported_tf_model`,(SELECTtitleASinputFROMbigquery-public-data.hacker_news.full))
The query results should look like this:

bq
Enter this command to run the query that usesML.PREDICT.
bq query \--use_legacy_sql=false \'SELECT *FROM ML.PREDICT( MODEL`bqml_tutorial.imported_tf_model`, (SELECT title AS input FROM`bigquery-public-data.hacker_news.full`))'
The results should look like this:
+------------------------------------------------------------------------+----------------------------------------------------------------------------------+| dense_1 | input |+------------------------------------------------------------------------+----------------------------------------------------------------------------------+| ["0.6251608729362488","0.2989124357700348","0.07592673599720001"] | How Red Hat Decides Which Open Source Companies t... || ["0.014276246540248394","0.972910463809967","0.01281337533146143"] | Ask HN: Toronto/GTA mastermind around side income for big corp. dev? || ["0.9821603298187256","1.8601855117594823E-5","0.01782100833952427"] | Ask HN: What are good resources on strategy and decision making for your career? || ["0.8611106276512146","0.06648492068052292","0.07240450382232666"] | Forget about promises, use harvests |+------------------------------------------------------------------------+----------------------------------------------------------------------------------+
API
Insert a new job andpopulate thejobs#configuration.queryproperty as in the request body. Replaceproject_id with the name of yourproject.
{"query":"SELECT * FROM ML.PREDICT(MODEL `project_id.bqml_tutorial.imported_tf_model`, (SELECT * FROM input_data))"}
BigQuery DataFrames
Before trying this sample, follow the BigQuery DataFrames setup instructions in theBigQuery quickstart using BigQuery DataFrames. For more information, see theBigQuery DataFrames reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up ADC for a local development environment.
Use thepredict function to run the TensorFlow model:
importbigframes.pandasasbpddf=bpd.read_gbq("bigquery-public-data.hacker_news.full")df_pred=df.rename(columns={"title":"input"})predictions=imported_tensorflow_model.predict(df_pred)predictions.head(5)The results should look like this:

In the query results, thedense_1 column contains an array ofprobability values, and theinput column contains the correspondingstring values from the input table. Each array element value representsthe probability that the corresponding input string is an article titlefrom a particular publication.
Clean up
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 the project
Console
gcloud
Delete individual resources
Alternatively, remove the individual resources used in this tutorial:
Optional:Delete the dataset.
What's next
- For an overview of BigQuery ML, seeIntroduction toBigQuery ML.
- To get started using BigQuery ML, seeCreate machine learningmodels in BigQuery ML.
- For more information about importing TensorFlow models, seeThe
CREATE MODELstatement for importing TensorFlowmodels. - For more information about working with models, see these resources:
- For more information on using the BigQuery DataFrames API in aBigQuery notebook, see:
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.