
Google Cloud named a leader in the Forrester Wave: Streaming Analytics
READ FULL INTRODOWNLOAD AGAIN4189
Of your peers have already downloaded this article
15:30 Minutes
The most insightful time you'll spend today!
Getting Started with BigQuery: 10 Quick Steps

3803
Of your peers have already read this article.
12:30 Minutes
The most insightful time you'll spend today!
BigQuery is Google’s fully managed, petabyte scale, low cost analytics data warehouse. BigQuery is NoOps—there is no infrastructure to manage and you don’t need a database administrator—so you can focus on analyzing data to find meaningful insights, use familiar SQL, and take advantage of our pay-as-you-go model.
That’s great, right?
So let’s get started. At the end of this, you will be able to you will use Google Cloud Client Libraries for .NET to query BigQuery public datasets with C#.
This quick course will go over:
- Setup and Requirements
- Enabling the BigQuery API
- Authenticating API requests
- Setup Access Control
- Installing the BigQuery client library for C#
- Query the works of Shakespeare
- Query the GitHub dataset
- Caching and statistics
- Loading data into BigQuery
An Expert’s Opinion on What Early-stage Startups Must Know

6468
Of your peers have already read this article.
3:00 Minutes
The most insightful time you'll spend today!
As lead for analytics and AI solutions at Google Cloud, my team works with startups building on Google Cloud. This puts us in the fortunate position to learn from founders and engineers about how early-stage startups’ investments can either constrain them or position them for success, even at the seed level. In this post, I want to share a few of the best practices to keep in mind as you’re building.
Understand your value proposition before diving into a technology stack
If you’re launching a startup in the cloud, you’re no doubt thinking about a technology stack, but it’s important to step back a bit and think carefully about the major value proposition that your startup offers to your customers. That value proposition is going to fundamentally drive the kind of technology that you should pick.
For example, does your system need processing in real time, or can it be done in a batch mode? Can you rely on once-a-day insights or do the insights have to come in as events happen?
Additionally, what kind of latency will your customers face? That latency makes your value proposition either usable or unusable. Early on in Google’s development, leaders realized that no one was going to wait more than a few hundred milliseconds for a web page to show them their results, and that realization drove the technology decisions that have allowed Google to scale from being a startup in a garage to being a trillion dollar company. Your startup needs to define its value to customers with this level of specificity before it can build a technology stack suited to its needs.
Focus on customer interactions
A few companies have gracefully pulled off big IT pivots that reshaped their value proposition. Netflix, for example, moved from mostly sending DVDs through the mail to becoming a streaming service and major content producer. That’s a huge shift in the user experience and the technology stack necessary to support it, even if the underlying value proposition (i.e., get content to customers) was broadly the same. But it’s also an outlier. If you’re planning for potential changes of this magnitude, rather than focused on getting your value proposition to users, you probably need to sharpen what that value proposition is.
Specifically, you need a clear vision of how customers will access and interact with your business. Typically, they’ll do so over a website or a mobile app, but there are still so many variables.
Are customers going to transmit documents? If so, in what format? Is handwriting supported or is input limited to typing? Can they use images for optical character recognition? Will it mostly be forms? Will the data be structured or unstructured? If all that sounds a little overwhelming, don’t worry, it’ll seem simpler by the end of this article—but also be aware: we’re just getting warmed up.
Imagine that most of your customers will access your business via voice, so you know you’ll want to prioritize conversational workflows. That’s a start—but dig deeper. Even if we suppose you’re usingDialogflow, a Google Cloud conversational AI platform that lets you build and deploy virtual agents, we’re still not really seeing the value proposition. How will all this work, from the beginning of a typical full customer interaction to the resolution? How many interactions will have to be facilitated over low-bandwidth connections, for example? When it comes to user interactions, make sure you can see an end-to-end use case.
Another example: you’re building a retail website, and one of your end-to-end use cases involves the customer asking if a certain amount of a given product is in stock, whether it’s one unit of the product, ten or hundreds. If the product is not sufficiently stocked, you want your app to offer similar items that are. Will your technology stack support this end-to-end use case?
These considerations are not an argument for premature optimization. There’s value in moving fast, getting minimum viable products to users, and then iterating. But in the early stages, you only get one chance to start on the right foot—and how you navigate that chance will influence a lot of dollars and effort down the road. You need to make sure you have business use cases, not just an idea, before you can start designing a technology stack.
Here’s how to get in the right frame of mind. Pick three use cases: two that are “bread and butter” and one that is technologically complex. Make sure your proposed technology stack can support all three, end to end.
Default toward higher levels of abstraction
Now that we’re in the right frame of mind, we’re ready to think about the technology stack more directly.
As a startup, you’ll need to conserve resources, and to do that, you’ll want to build at the highest level of abstraction possible for your value proposition. For example, you probably don’t want your people setting up clusters. You don’t want them configuring things if they can use a fully managed service. You want them focused on building your prototype, not managing infrastructure.

This focus has definitely informed how we create products at Google Cloud, as our canonical data stack—Pub/Sub, Dataflow, BigQuery, and Vertex AI—consists of auto-scaling and serverless products.
But management of infrastructure is not the only place where you should err toward a less-is-more philosophy.
When it comes to architecture, choose no-code over low-code and low-code over writing custom code. For example, rather than writing ETL pipelines to transform the data you need before you land it into BigQuery, you could use pre-built connectors to directly land the raw data into BigQuery. That’s no code right there. Then, transform the data into the form you need using SQL views directly in the data warehouse. This is called ELT, and it is low code. You will be a lot more agile if you choose an ELT approach over an ETL approach.
Another place is when you choose your ML modeling framework. Don’t start with custom TensorFlow models. Start with AutoML. That’s no-code. You can invoke AutoML directly from BigQuery, avoiding the need to build complex data and ML pipelines. If necessary, move on to pre-built models from TensorFlow Hub, HuggingFace, etc. That’s low-code. Build your own custom ML models only as a last resort.

Focus on getting your vision to market, not chasing technology hype
The goal is to pick the right technology stack for bringing your vision to market, generating value for customers, conserving resources, and maintaining flexibility for growth. Early IT investments should usually gravitate toward things that preserve flexibility, such as managed services built on standard protocols or open APIs, but they needn’t always rush to the flashiest technologies. The answer isn’t always ML, for example. The answer might be heuristics to start, with a path to ML once you have collected enough data. You want to make sure that your intelligence layer has enough abstraction so you can mark it up with simple rules at first, but then replace it with a more robust system as you go along.
Launch and iterate fast with these principles
The preceding discussion is a reminder that your most expensive resource is your people—and that you really want them to be focused on building your prototype, minimum viable product or production app You want to launch fast and iterate fast, and the only way you can do that is by focusing on the things that differentiate you.
But regardless of the technologies you use, the bottom line is the same: follow these four principles.
- Figure out your major value proposition and design your tech stack around it.
- Be very careful about user interactions. User experience is super important; you need to make sure you deliver the kind of experience that your customers have grown to expect.
- When you’re building, pick the highest possible level of abstraction possible—the most fully managed tools and no-code/low-code frameworks that give you the functionality that you need.
- Instead of choosing new or flashy technologies, consider if you can build a “good enough” minimum viable product quickly and come back to a better implementation later.
To learn more about why startups are choosing Google Cloud, click here.
2022 Healthcare Trends: Healthcare Data, M&As, Better Patient Care, AI in Drug Development & Strategic Partnerships

6620
Of your peers have already read this article.
3:00 Minutes
The most insightful time you'll spend today!
The COVID-19 pandemic continues to push the healthcare and life sciences industry in entirely new ways. In record time, we’ve witnessed public health officials, vaccine developers, equipment manufacturers, and essential workers take life saving actions—regularly putting their own lives at risk—to respond to the exceptional challenges of our time.
Yet after all the turmoil and uncertainty of the pandemic, record breaking levels of investment continue to come into the market to fuel innovations.
Vaccine development is now measured in weeks rather than years; providers are leveraging telehealth technologies to improve the physician and patient experience; and individuals have embraced a variety of devices to assume greater ownership and control of their personal health.
With that in mind, here are five of the many innovations I see driving healthcare and life sciences for at least the next 12 months:
1. Unleashing the power of healthcare and life sciences data
People have arguably never had as much access and understanding to their personal health data than they can in 2022. They have the ability to understand their genetic makeup, medical history, family history, and activity levels to ensure they are living a healthy lifestyle. Taken together, this longitudinal profile can become the basis for more personalized medicine. Add wearable devices to the mix and patients gain real- or near-real-time updates on their health status.
Further, global regulatory agencies have continued to mandate the need for providers to maintain a longitudinal health record that provides a holistic view of the patient across all the encounters they have had with a health system. Physician surveys conducted by the The Harris Poll and Google Cloud show that a 360-degree view of the patient, across all provider encounters, leads to faster, more accurate diagnosis, and better outcomes.
If secure data access and interoperability can begin to include insurers, researchers, public health officials, and others in the field, the powerful network effects benefiting patients will only grow. When combined with those longitudinal phenome profiles, the opportunities for personalized and preventative medicine enter a whole new era.
2. Healthcare and life sciences M&A boom continues
Although the pandemic initially slowed activity on mergers and acquisitions in the early part of 2020, the healthcare and life sciences industry has seen a rapid rebound and acceleration of deals ever since. The success of COVID-19 vaccines, the importance of telehealth, and the focus on molecular modeling and genomic-based drug development have all boosted investment as organizations look to enter new markets, develop new therapies, and leverage low interest rates while they last.
In 2021, the total funding of US digital health startups surpassed $29 billion across 729 deals, according to advisory Rock Health. That’s almost double the levels of 2020, which itself set records. Analysts at PWC meanwhile estimate M&A investments in biopharmaceutical and life sciences could approach $400 billion this year across all sub-sectors
Clearly, the pandemic has been a primary driver of investment as the focus on healthcare has dramatically increased. Yet the increased activity also reflects changing business models and emerging technologies that are now required to compete in the rapidly evolving space. For organizations to capitalize on these investments, it will take not only great vision and intellectual property but also the right technologies—like cloud—and the right data interoperability models, to make partnerships and acquisitions more scalable, feasible, and seamless.
3. Transforming the patient experience at a new rate
The pandemic has shined a spotlight on the inefficiencies and complexities that exist in healthcare markets across the globe. As wave after wave has surged, global healthcare systems remain overwhelmed on most every aspect of patients’ treatment journeys. Even before COVID-19, healthcare was already one of the largest spend areas for governments around the world. The pandemic has only exacerbated the known issues.
Clearly, administrators, regulators, physicians, nurses, and patients would agree that the processes and models need to change. There’s a need to maintain this momentum and even increase the tempo to achieve lasting change.
Take telehealth. Within months of the start of the pandemic, providers moved to provide more remote capabilities so physicians could still meet with patients virtually to ensure health and safety on all sides. Payers recognized the importance of telehealth and began to update reimbursement rules. And organizations are now reimagining policies in areas such as prior authorization, submission, and adjudication to reduce complexity and bureaucracy while improving responsiveness.
Looking beyond the system, organizations are also recognizing and deepening their understanding of the structural and social determinants of health that impact patient care and health outcomes, especially for historically underserved communities. Private and public sectors are learning from, and increasingly partnering with, the social sciences, public health, biomedical informatics, computer science, public policy and community groups around how to build a mI’ore equitable and inclusive consumer products and Health IT strategies.
The newfound levels of transparency, visibility, and accountability that patients, caregivers, and organizations are achieving will ultimately increase competition and provide a more effective, equitable, efficient and, above all, healthier marketplace for all patients. As we move past the worst of the pandemic, regulators and organizations should keep fighting for progress over business as usual.
4. AI is now a core competency for Drug Development
The ability of organizations like Pfizer, Moderna, Johnson & Johnson, and Astrazeneca to develop COVID-19 vaccines has been a remarkable accomplishment—particularly the historic speed with which they were created and deployed. This innovation acceleration was largely enabled by the use of new drug development platforms that allow researchers to use artificial intelligence and machine learning to model protein and cellular interactions to rapidly advance the science.
No longer must researchers rely on traditional laboratory testing (and retesting). With their improved understanding of the molecular and genetic structure of a patient and, for example, their tumor, researchers can use AI to enable simulations on computers rather than testing in live conditions. This technology can process thousands, even millions of simulations to help identify high-potential candidates for treatment consideration and subsequent analysis.
AI-enabled drug discovery models can eliminate months and years from the research process, which can reduce the time to develop a drug and accelerate the time to treatment for an individual patient. As just one example, consider the work on AlphaFold2 by Google’s DeepMind unit who leverages AI to predict effective protein shapes for new drugs. Healthcare and life sciences organizations already recognize the potential of AI. Now comes the investments to leverage this rapidly evolving technology to support their efforts now and in the future.
5. Ecosystem partnerships tackle complexity and spur innovation
As the importance and growth of the healthcare and life sciences industry continues, we will see even more new players and partnerships emerging to address old problems in new ways. This trend will touch all aspects of the healthcare value chain and will, increasingly, see three- and four-player partnerships emerge to address the complex challenges of today’s healthcare marketplace.
Technology will continue to play a key role as capabilities and platforms will transform all aspects of the marketplace. Cell phones, wearable devices, and other technologies will provide real-time updates and notifications to patients on everything from glucose levels to payments for healthcare services. Voice recognition software will document physician and patient discussions to reduce the burden of record keeping. Real-world data will be used to simplify and confidentially recruit patients for participation in clinical trials.
New players will continue to enter the market to improve health outcomes and reduce costs. Major retailers are among the companies extending their pharmacies to provide additional diagnostic and concierge services, saving patients from additional appointments while boosting prevention. Community organizations are emerging to help identify and care for underserved communities whose health outcomes are significantly lower than the average patient.
For all the exhausting and heart-wrenching challenges of the past two years, the opportunities the pandemic has laid bare cannot be overlooked. We owe it to those who have worked and fought so hard for every life to forge even more new partnerships—and make it easier to do so—so that the next crisis, when it does arise, will never be as bad as the one we’re now conquering. Technology can be the enabler in this effort and help bring us together to continue to conquer the challenges that lie ahead.
How Vertex AI NAS is Suitable for Most Advanced ML Workloads

4475
Of your peers have already read this article.
3:00 Minutes
The most insightful time you'll spend today!
Vertex AI launched with the premise “one AI platform, every ML tool you need.” Let’s talk about how Vertex AI streamlines modeling universally for a broad range of use cases.
The overall purpose of Vertex AI is to simplify modeling so that enterprises can fast track their innovation, accelerate time to market, and ultimately increase return on ML investments. Vertex AI facilitates this in several ways. Features like Vertex AI Workbench, for example, speed up training and deployment of models by five times compared to traditional notebooks. Vertex AI Workbench’s native integration with BigQuery and Spark means that users without data science expertise can more easily perform machine learning work. Tools integrated into the unified Vertex AI platform, such as state of the art pre-trained APIs and AutoML, make it easier for data scientists to build models in less time. And for modeling work that lends itself best to custom modeling, Vertex AI’s custom model tooling supports advanced ML coding, with nearly 80% fewer lines of code required (compared to competitive platforms) to train a model with custom libraries. Vertex AI delivers all this while maintaining a strong focus on Explainable AI.
Yet organizations with the largest investments in AI and machine learning, with teams of ML experts, require extremely advanced toolsets to deliver on their most complex problems. Simplified ML modeling isn’t relegated to simple use cases only.
Let’s look at Vertex AI Neural Architecture Search (NAS), for instance.
Vertex AI NAS enables ML experts at the highest level to perform their most complex tasks with higher accuracy, lower latency, and low power requirements. Vertex AI NAS originates from the deep experience Alphabet has with building advanced AI at scale. In 2017, the Google Brain team recognized we need a better way to scale AI modeling, so they developed Neural Architecture Search technology to create an AI that generates other neural networks, trained to optimize their performance in a specific task the user provides. To the astonishment of many in the field, these AI-optimized models were able to beat a number of state of the art benchmarks, such as ImageNet and SOTA mobilenets, setting a new standard for many of the applications we see in use today, including many Google-internal products. Google Cloud saw the potential of such a technology and shipped in less than a year a productized version of the technique (under the brand AutoML). Vertex AI NAS is the newest and most powerful version of this idea, using the most sophisticated innovation that has emerged since the initial research.
Customer organizations are already implementing Vertex AI NAS for their most advanced workloads. Autonomous vehicle company Nuro is using Vertex AI NAS, and Jack Guo, Head of Autonomy Platform at the company, states, “Nuro’s perception team has accelerated their AI model development with Vertex AI NAS. Vertex AI NAS have enabled us to innovate AI models to achieve good accuracy and optimize memory and latency for the target hardware. Overall, this has increased our team’s productivity for developing and deploying perception AI models.”
And our partner ecosystem is growing for Vertex AI NAS. Google Cloud and Qualcomm Technologies have collaborated to bring Vertex AI NAS to the Qualcomm Technologies Neural Processing SDK, optimized for Snapdragon 8. This will bring AI to different device types and use cases, such as those involving IoT, mixed reality, automobiles, and mobile.
Google Cloud’s commitments to making machine learning more accessible and useful for data users, from the novice to the expert, and to increasing the efficacy of machine learning for enterprises are at the core of everything we do. With the suite of unified machine learning tools within Vertex AI, organizations can take advantage of every ML tool they need on one AI platform.
Ready to start ML modeling with Vertex AI? Start building for free. Want to know how Vertex AI Platform can help your enterprise increase return on ML investments? Contact us.
10180
Of your peers have already watched this video.
1:00 Minutes
The most insightful time you'll spend today!
Predict User Churn on Gaming Apps with Google Analytics Data using BigQuery ML
User retention can be a major challenge for mobile game developers. According to the Mobile Gaming Industry Analysis in 2019, most mobile games only see a 25% retention rate for users after the first day. To retain a larger percentage of users after their first use of an app, developers can take steps to motivate and incentivize certain users to return. But to do so, developers need to identify the propensity of any specific user returning after the first 24 hours.
In this blog post, we will discuss how you can use BigQuery ML to run propensity models on Google Analytics 4 data from your gaming app to determine the likelihood of specific users returning to your app.
You can also use the same end-to-end solution approach in other types of apps using Google Analytics for Firebase as well as apps and websites using Google Analytics 4. To try out the steps in this blogpost or to implement the solution for your own data, you can use this Jupyter Notebook.
Using this blog post and the accompanying Jupyter Notebook, you’ll learn how to:
- Explore the BigQuery export dataset for Google Analytics 4
- Prepare the training data using demographic and behavioural attributes
- Train propensity models using BigQuery ML
- Evaluate BigQuery ML models
- Make predictions using the BigQuery ML models
- Implement model insights in practical implementations
Google Analytics 4 (GA4) properties unify app and website measurement on a single platform and are now default in Google Analytics. Any business that wants to measure their website, app, or both, can use GA4 for a more complete view of how customers engage with their business. With the launch of Google Analytics 4, BigQuery export of Google Analytics data is now available to all users. If you are already using a Google Analytics 4 property, you can follow this guide to set up exporting your GA data to BigQuery.
Once you have set up the BigQuery export, you can explore the data in BigQuery. Google Analytics 4 uses an event-based measurement model. Each row in the data is an event with additional parameters and properties. The Schema for BigQuery Export can help you to understand the structure of the data.
In this blogpost, we use the public sample export data from an actual mobile game app called “Flood It!” (Android, iOS) to build a churn prediction model. But you can use data from your own app or website.
Here’s what the data looks like. Each row in the dataset is a unique event, which can contain nested fields for event parameters.
SELECT *FROM `firebase-public-project.analytics_153293282.events_*`TABLESAMPLE SYSTEM (1 PERCENT)

This dataset contains 5.7M events from over 15k users.
SELECTCOUNT(DISTINCT user_pseudo_id) as count_distinct_users,COUNT(event_timestamp) as count_eventsFROM`firebase-public-project.analytics_153293282.events_*

Our goal is to use BigQuery ML on the sample app dataset to predict propensity to user churn or not churn based on users’ demographics and activities within the first 24 hours of app installation.

In the following sections, we’ll cover how to:
- Pre-process the raw event data from GA4
- Identify users & the label feature
- Process demographic features
- Process behavioral features
- Train classification model using BigQuery ML
- Evaluate the model using BigQueryML
- Make predictions using BigQuery ML
- Utilize predictions for activation
Pre-process the raw event data
You cannot simply use raw event data to train a machine learning model as it would not be in the right shape and format to use as training data. So in this section, we’ll go through how to pre-process the raw data into an appropriate format to use as training data for classification models.
This is what the training data should look like for our use case at the end of this section:

Notice that in this training data, each row represents a unique user with a distinct user ID (user_pseudo_id).
Identify users & the label feature
We first filtered the dataset to remove users who were unlikely to return the app anyway. We defined these ‘bounced’ users as ones who spent less than 10 mins with the app. Then we labeled all remaining users:
- churned: No event data for the user after 24 hours of first engaging with the app.
- returned: The user has at least one event record after 24 hours of first engaging with the app.
For your use case, you can have a different definition of bounce and churning. Also you can even try to predict something else other than churning, e.g.:
- whether a user is likely to spend money on in-game currency
- likelihood of completing n-number of game levels
- likelihood of spending n amount of time in-game etc.
In such cases, label each record accordingly so that whatever you are trying to predict can be identified from the label column.
From our dataset, we found that ~41% users (5,557) bounced. However, from the remaining users (8,031), ~23% (1,883) churned after 24 hours:
SELECTbounced,churned,COUNT(churned) as count_usersFROMbqmlga4.returningusersGROUP BY 1,2ORDER BY bounced

To create these bounced and churned columns, we used the following snippet of SQL code.
...#churned = 1 if last_touch within 24 hr of app installation, else 0IF (user_last_engagement < TIMESTAMP_ADD(user_first_engagement,INTERVAL 24 HOUR),1,0 ) AS churned,#bounced = 1 if last_touch within 10 min, else 0IF (user_last_engagement <= TIMESTAMP_ADD(user_first_engagement,INTERVAL 10 MINUTE),1,0 ) AS bounced,...
You can view the Jupyter Notebook for the full query used for materializing the bounced and churned labels.
Process demographic features
Next, we added features both for demographic data and for behavioral data spanning across multiple columns. Having a combination of both demographic data and behavioral data helps to create a more predictive model.
We used the following fields for each user as demographic features:
geo.countrydevice.operating_systemdevice.language
A user might have multiple unique values in these fields — for example if a user uses the app from two different devices. To simplify, we used the values from the very first user engagement event.
CREATE OR REPLACE VIEW bqmlga4.user_demographics AS (WITH first_values AS (SELECTuser_pseudo_id,geo.country as country,device.operating_system as operating_system,device.language as language,ROW_NUMBER() OVER (PARTITION BY user_pseudo_id ORDER BY event_timestamp DESC) AS row_numFROM `firebase-public-project.analytics_153293282.events_*`WHERE event_name="user_engagement")SELECT * EXCEPT (row_num)FROM first_valuesWHERE row_num = 1 #first engagement);
Process behavioral features
There is additional demographic information present in the GA4 export dataset, e.g. app_info, device, event_params, geo etc. You may also send demographic information to Google Analytics through each hit via user_properties. Furthermore, if you have first-party data on your own system, you can join that with the GA4 export data based on user_ids.
To extract user behavior from the data, we looked into the user’s activities within the first 24 hours of first user engagement. In addition to the events automatically collected by Google Analytics, there are also the recommended events for games that can be explored to analyze user behavior. For our use case, to predict user churn, we counted the number of times the follow events were collected for a user within 24 hours of first user engagement:
user_engagementlevel_start_quickplaylevel_end_quickplaylevel_complete_quickplaylevel_reset_quickplaypost_scorespend_virtual_currencyad_rewardchallenge_a_friendcompleted_5_levelsuse_extra_steps
The following query shows how these features were calculated:
WITHevents_first24hr AS (SELECTe.*FROM`firebase-public-project.analytics_153293282.events_*` eJOINbqmlga4.returningusers rONe.user_pseudo_id = r.user_pseudo_idWHERETIMESTAMP_MICROS(e.event_timestamp) <= r.ts_24hr_after_first_engagement)SELECTuser_pseudo_id,SUM(IF(event_name = 'user_engagement', 1, 0)) AS cnt_user_engagement,# ... repeated for all behavior data ...SUM(IF(event_name = 'use_extra_steps', 1, 0)) AS cnt_use_extra_steps,FROMevents_first24hrGROUP BY1
View the notebook for the query used to aggregate and extract the behavioral data. You can use different sets of events for your use case. To view the complete list of events, use the following query:
SELECTevent_name,COUNT(event_name) as event_countFROM`firebase-public-project.analytics_153293282.events_*`GROUP BY 1ORDER BYevent_count DESC
After this we combined the features to ensure our training dataset reflects the intended structure. We had the following columns in our table:
- User ID:
user_pseudo_id
- Label:
churned
- Demographic features
countrydevice_osdevice_language
- Behavioral features
cnt_user_engagementcnt_level_start_quickplaycnt_level_end_quickplaycnt_level_complete_quickplaycnt_level_reset_quickplaycnt_post_scorecnt_spend_virtual_currencycnt_ad_rewardcnt_challenge_a_friendcnt_completed_5_levelscnt_use_extra_stepsuser_first_engagement
At this point, the dataset was ready to train the classification machine learning model in BigQuery ML. Once trained, the model will output a propensity score between churn (churned=1) or return (churned=0) indicating the probability of a user churning based on the training data.
Train classification model
When using the CREATE MODEL statement, BigQuery ML automatically splits the data between training and test. Thus the model can be evaluated immediately after training (see the documentation for more information).
For the ML model, we can choose among the following classification algorithms where each type has its own pros and cons:

Often logistic regression is used as a starting point because it is the fastest to train. The query below shows how we trained the logistic regression classification models in BigQuery ML.
CREATE OR REPLACE MODEL bqmlga4.churn_logregTRANSFORM(EXTRACT(MONTH from user_first_engagement) as month,EXTRACT(DAYOFYEAR from user_first_engagement) as julianday,EXTRACT(DAYOFWEEK from user_first_engagement) as dayofweek,EXTRACT(HOUR from user_first_engagement) as hour,* EXCEPT(user_first_engagement, user_pseudo_id))OPTIONS(MODEL_TYPE="LOGISTIC_REG",INPUT_LABEL_COLS=["churned"]) ASSELECT*FROMbqmlga4.train
We extracted month, julianday, and dayofweek from datetimes/timestamps as one simple example of additional feature preprocessing before training. Using TRANSFORM() in your CREATE MODEL query allows the model to remember the extracted values. Thus, when making predictions using the model later on, these values won’t have to be extracted again. View the notebook for the example queries to train other types of models (XGBoost, deep neural network, AutoML Tables).
Evaluate model
Once the model finished training, we ran ML.EVALUATE to generate precision, recall, accuracy and f1_score for the model:
SELECT*FROMML.EVALUATE(MODEL bqmlga4.churn_logreg)

The optional THRESHOLD parameter can be used to modify the default classification threshold of 0.5. For more information on these metrics, you can read through the definitions on precision and recall, accuracy, f1-score, log_loss and roc_auc. Comparing the resulting evaluation metrics can help to decide among multiple models.Furthermore, we used a confusion matrix to inspect how well the model predicted the labels, compared to the actual labels. The confusion matrix is created using the default threshold of 0.5, which you may want to adjust to optimize for recall, precision, or a balance (more information here).
SELECTexpected_label,_0 AS predicted_0,_1 AS predicted_1FROMML.CONFUSION_MATRIX(MODEL bqmlga4.churn_logreg)

This table can be interpreted in the following way:

Make predictions using BigQuery ML
Once the ideal model was available, we ran ML.PREDICT to make predictions. For propensity modeling, the most important output is the probability of a behavior occurring. The following query returns the probability that the user will return after 24 hrs. The higher the probability and closer it is to 1, the more likely the user is predicted to return, and the closer it is to 0, the more likely the user is predicted to churn.
SELECTuser_pseudo_id,returned,predicted_returned,predicted_returned_probs[OFFSET(0)].prob as probability_returnedFROMML.PREDICT(MODEL bqmlga4.churn_logreg,(SELECT * FROM bqmlga4.train)) #can be replaced with a proper test dataset
Utilize predictions for activation
Once the model predictions are available for your users, you can activate this insight in different ways. In our analysis, we used user_pseudo_id as the user identifier. However, ideally, your app should send back the user_id from your app to Google Analytics. In addition to using first-party data for model predictions, this will also let you join back the predictions from the model into your own data.
- You can import the model predictions back into Google Analytics as a user attribute. This can be done using the Data Import feature for Google Analytics 4. Based on the prediction values you can Create and edit audiences and also do Audience targeting. For example, an audience can be users with prediction probability between 0.4 and 0.7, to represent users who are predicted to be “on the fence” between churning and returning.
- For Firebase Apps, you can use the Import segments feature. You can tailor user experience by targeting your identified users through Firebase services such as Remote Config, Cloud Messaging, and In-App Messaging. This will involve importing the segment data from BigQuery into Firebase. After that you can send notifications to the users, configure the app for them, or follow the user journeys across devices.
- Run targeted marketing campaigns via CRMs like Salesforce, e.g. send out reminder emails.
You can find all of the code used in this blogpost in the Github repository:
What’s next?
Continuous model evaluation and re-training
As you collect more data from your users, you may want to regularly evaluate your model on fresh data and re-train the model if you notice that the model quality is decaying.
Continuous evaluation—the process of ensuring a production machine learning model is still performing well on new data—is an essential part in any ML workflow. Performing continuous evaluation can help you catch model drift, a phenomenon that occurs when the data used to train your model no longer reflects the current environment.
To learn more about how to do continuous model evaluation and re-train models, you can read the blogpost: Continuous model evaluation with BigQuery ML, Stored Procedures, and Cloud Scheduler
More resources
If you’d like to learn more about any of the topics covered in this post, check out these resources:
- BigQuery export of Google Analytics data
- BigQuery ML quickstart
- Events automatically collected by Google Analytics 4
- Qwiklabs: Create ML models with BigQuery ML
Or learn more about how you can use BigQuery ML to easily build other machine learning solutions:
- How to build demand forecasting models with BigQuery ML
- How to build a recommendation system on e-commerce data using BigQuery ML
Let us know what you thought of this post, and if you have topics you’d like to see covered in the future! You can find us on Twitter at @polonglin and @_mkazi_.Thanks to reviewers: Abhishek Kashyap, Breen Baker, David Sabater Dinter.
More Relevant Stories for Your Company

Home Depot’s Interconnected Retail Experience by Virtue of Google Cloud Migration for SAP Applications
With nearly 2,300 stores, The Home Depot is the world’s largest home-improvement chain — a brand that professional contractors and DIYers alike have come to depend on. The home improvement industry continues to experience unprecedented demand and dramatic increases in online ordering accompanied by expanding consumer expectations for things like

DocAI Lowers Customer’s Document Processing Cost by 60 Percent. Learn How
Some of the most important data at your company isn’t living in databases, but in documents, and most business processes begin, involve or end with a document. Yet most companies are still manually entering data and reliant on guesswork to make sense of it all as the volume and variety

Wayfair Writes its Success Story with BigQuery for Internal Analytics
Editor’s note: Home-goods and furniture giant Wayfair first partnered up with Google Cloud to transform and scale its storefront—work that proved its value many times over during the unprecedented surge in ecommerce traffic during 2020. Today, we hear how BigQuery’s performance and cost optimization have transformed the company’s internal analytics

How Google Cloud & NGIS’ Partnership Powers Sustainability & Responsible Sourcing for Consumer Brands
In the competitive world of consumer goods, sustainability matters more than ever. In recent Google survey, 82% of consumers said sustainability is more top of mind now than it was before COVID-191 and 78% said that big businesses have a role to play in helping to fight climate change.2 As well as delivering on






