Get data insights from a contribution analysis model using a summable ratio metric
In this tutorial, you use acontribution analysis model to analyzethe contribution of the cost of sales ratio in the Iowa liquorsales dataset. This tutorial 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 ratio metric.This type of model summarizes the values of two numeric columns anddetermines the ratio differences across the control and test dataset for each segment of the data.
- 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 followingquery creates two intermediate tables, a test table for liquor data from 2021and a control table with liquor data from 2020, and then performs a union ofthe intermediate tables to create a table with both test and control rowsand the same set of columns.
In the Google Cloud console, go to theBigQuery page.
In the query editor, run the following statement:
CREATEORREPLACETABLEbqml_tutorial.iowa_liquor_sales_dataAS(SELECTstore_name,city,vendor_name,category_name,item_description,SUM(sale_dollars)AStotal_sales,SUM(state_bottle_cost)AStotal_bottle_cost,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,SUM(state_bottle_cost)AStotal_bottle_cost,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.liquor_sales_modelOPTIONS(model_type='CONTRIBUTION_ANALYSIS',contribution_metric='sum(total_bottle_cost)/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_data;
The query takes approximately 35 seconds to complete, after which the modelliquor_sales_model appears in thebqml_tutorial dataset. Because thequery uses aCREATE MODEL statement to create a model, there are no queryresults.
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 ratio metric contribution analysis model:
SELECTcontributors,metric_test,metric_control,metric_test_over_metric_control,metric_test_over_complement,metric_control_over_complement,aumann_shapley_attribution,apriori_supportcontributionFROMML.GET_INSIGHTS(MODEL`bqml_tutorial.liquor_sales_model`)ORDERBYaumann_shapley_attributionDESC;
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 | metric_test_over_metric_control | metric_test_over_complement | metric_control_over_complement | aumann_shapley_attribution | apriori_support | contribution |
|---|---|---|---|---|---|---|---|---|
| all | 0.069 | 0.071 | 0.969 | null | null | -0.00219 | 1.0 | 0.00219 |
| city=DES MOINES | 0.048 | 0.054 | 0.88 | 0.67 | 0.747 | -0.00108 | 0.08 | 0.00108 |
| vendor_name=DIAGEO AMERICAS | 0.064 | 0.068 | 0.937 | 0.917 | 0.956 | -0.0009 | 0.184 | 0.0009 |
| vendor_name=BACARDI USA INC | 0.071 | 0.082 | 0.857 | 1.025 | 1.167 | -0.00054 | 0.057 | 0.00054 |
| vendor_name=PERNOD RICARD USA | 0.068 | 0.077 | 0.89 | 0.988 | 1.082 | -0.0005 | 0.061 | 0.0005 |
In the output, you can see that the data segmentcity=DES MOINEShas the highestcontribution of change in the sales ratio. You can also see this differencein themetric_test andmetric_control columns, which show that the ratiodecreased in the test data compared to the control data. Other metrics,such asmetric_test_over_metric_control,metric_test_over_complement,andmetric_control_over_complement, compute additional statistics thatdescribe the relationship between the control and test ratios and how theyrelate to the overall population. For more information, seeOutput for summable ratio metric contribution analysis models.
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.