Get data insights from a contribution analysis modelusing a summable metric
In this tutorial, you use acontribution analysis model to analyzesales changes between 2020 and 2021 in the Iowa liquor sales dataset. Thistutorial guides you through performing the following tasks:
- Create an input table based on publicly available Iowa liquor data.
- Create acontribution analysis model that uses asummable metric.This type of model summarizes a given metric for a combination of one ormore dimensions in the data, to determine how those dimensions contributeto the metric value.
- Get the metric insights from the model by using the
ML.GET_INSIGHTSfunction.
Before starting this tutorial, you should be familiar with thecontribution analysis use case.
Required permissions
To create the dataset, you need the
bigquery.datasets.createIdentity and Access Management (IAM) permission.To create the model, you need the following permissions:
bigquery.jobs.createbigquery.models.createbigquery.models.getDatabigquery.models.updateData
To run inference, you need the following permissions:
bigquery.models.getDatabigquery.jobs.create
Costs
In this document, you use the following billable components of Google Cloud:
- BigQuery ML: You incur costs for the data that you process in BigQuery.
To generate a cost estimate based on your projected usage, use thepricing calculator.
For more information about BigQuery pricing, seeBigQuery pricing inthe BigQuery documentation.
Before you begin
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.
Enable the BigQuery API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.
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)Create a table of input data
Create a table that contains test and control data to analyze. The test tablecontains liquor data from 2021 and the control table contains liquor data from2020. The following query combines the test and control data into a singleinput table:
In the Google Cloud console, go to theBigQuery page.
In the query editor, run the following statement:
CREATEORREPLACETABLEbqml_tutorial.iowa_liquor_sales_sum_dataAS((SELECTstore_name,city,vendor_name,category_name,item_description,SUM(sale_dollars)AStotal_sales,FALSEASis_testFROM`bigquery-public-data.iowa_liquor_sales.sales`WHEREEXTRACT(YEARfromdate)=2020GROUPBYstore_name,city,vendor_name,category_name,item_description,is_test)UNIONALL(SELECTstore_name,city,vendor_name,category_name,item_description,SUM(sale_dollars)AStotal_sales,TRUEASis_testFROM`bigquery-public-data.iowa_liquor_sales.sales`WHEREEXTRACT(YEARFROMdate)=2021GROUPBYstore_name,city,vendor_name,category_name,item_description,is_test));
Create the model
Create a contribution analysis model:
In the Google Cloud console, go to theBigQuery page.
In the query editor, run the following statement:
CREATEORREPLACEMODELbqml_tutorial.iowa_liquor_sales_sum_modelOPTIONS(model_type='CONTRIBUTION_ANALYSIS',contribution_metric='sum(total_sales)',dimension_id_cols=['store_name','city','vendor_name','category_name','item_description'],is_test_col='is_test',min_apriori_support=0.05)ASSELECT*FROMbqml_tutorial.iowa_liquor_sales_sum_data;
The query takes approximately 60 seconds to complete, after which the modeliowa_liquor_sales_sum_model appears in thebqml_tutorial dataset. Becausethe query uses aCREATE MODEL statement to create a model, there are noquery results.
Get insights from the model
Get insights generated by the contribution analysis model by using theML.GET_INSIGHTS function.
In the Google Cloud console, go to theBigQuery page.
In the query editor, run the following statement to select columns from theoutput for a summable metric contribution analysis model:
SELECTcontributors,metric_test,metric_control,difference,relative_difference,unexpected_difference,relative_unexpected_difference,apriori_support,contributionFROMML.GET_INSIGHTS(MODEL`bqml_tutorial.iowa_liquor_sales_sum_model`);
The first several rows of the output should look similar to the following.The values are truncated to improve readability.
| contributors | metric_test | metric_control | difference | relative_difference | unexpected_difference | relative_unexpected_difference | apriori_support | contribution |
|---|---|---|---|---|---|---|---|---|
| all | 428068179 | 396472956 | 31595222 | 0.079 | 31595222 | 0.079 | 1.0 | 31595222 |
| vendor_name=SAZERAC COMPANY INC | 52327307 | 38864734 | 13462573 | 0.346 | 11491923 | 0.281 | 0.122 | 13462573 |
| city=DES MOINES | 49521322 | 41746773 | 7774549 | 0.186 | 4971158 | 0.111 | 0.115 | 7774549 |
| vendor_name=DIAGEO AMERICAS | 84681073 | 77259259 | 7421814 | 0.096 | 1571126 | 0.018 | 0.197 | 7421814 |
| category_name=100% AGAVE TEQUILA | 23915100 | 17252174 | 6662926 | 0.386 | 5528662 | 0.3 | 0.055 | 6662926 |
The output is automatically sorted by contribution, orABS(difference), indescending order. In theall row, thedifference column shows there was a$31,595,222 increase in total sales from 2020 to 2021, a 7.9% increase asindicated by therelative_difference column. In the second row, withvendor_name=SAZERAC COMPANY INC, there was anunexpected_difference of$11,491,923, meaning this segment of data grew 28% more than the growth rate ofthe data as a whole, as seen from therelative_unexpected_difference column.For more information, see thesummable metric output columns.
Clean up
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-16 UTC.