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 theML.GET_INSIGHTS function.

Before starting this tutorial, you should be familiar with thecontribution analysis use case.

Required permissions

  • To create the dataset, you need thebigquery.datasets.createIdentity and Access Management (IAM) permission.

  • To create the model, you need the following permissions:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
  • To run inference, you need the following permissions:

    • bigquery.models.getData
    • bigquery.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.

New Google Cloud users might be eligible for afree trial.

For more information about BigQuery pricing, seeBigQuery pricing inthe BigQuery documentation.

Before you begin

  1. 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

    • 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.create permission.Learn how to grant roles.
    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.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. 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.enable permission.Learn how to grant roles.

    Enable the API

Create a dataset

Create a BigQuery dataset to store your ML model.

Console

  1. In the Google Cloud console, go to theBigQuery page.

    Go to the BigQuery page

  2. In theExplorer pane, click your project name.

  3. ClickView actions > Create dataset

  4. On theCreate dataset page, do the following:

    • ForDataset ID, enterbqml_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.

  1. Create a dataset namedbqml_tutorial with 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--dataset flag, the command uses the-d shortcut.If you omit-d and--dataset, the command defaults to creating adataset.

  2. 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:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. 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:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. 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.

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. 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.

contributorsmetric_testmetric_controldifferencerelative_differenceunexpected_differencerelative_unexpected_differenceapriori_supportcontribution
all428068179396472956315952220.079315952220.0791.031595222
vendor_name=SAZERAC COMPANY INC5232730738864734134625730.346114919230.2810.12213462573
city=DES MOINES495213224174677377745490.18649711580.1110.1157774549
vendor_name=DIAGEO AMERICAS846810737725925974218140.09615711260.0180.1977421814
category_name=100% AGAVE TEQUILA239151001725217466629260.38655286620.30.0556662926

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

    Caution: Deleting a project has the following effects:
    • Everything in the project is deleted. If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
    • Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as anappspot.com URL, delete selected resources inside the project instead of deleting the whole project.

    If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.

  1. In the Google Cloud console, go to theManage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then clickDelete.
  3. In the dialog, type the project ID, and then clickShut down to delete the project.

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.