arrow_back

Analyzing Natality Data Using Vertex AI and BigQuery

Join Sign in

Analyzing Natality Data Using Vertex AI and BigQuery

30 minutes 5 Credits

GSP012

Google Cloud self-paced labs logo

Overview

In this lab, you analyze a large (137 million rows) natality dataset using BigQuery and Vertex AI.

What you learn

In this lab, you:

  • Launch Vertex AI notebook
  • Invoke a BigQuery query
  • Create charts in Jupyter
  • Export data for machine learning

This lab illustrates how you can carry out data exploration of large datasets, but continue to use familiar tools like Pandas and Jupyter. The trick is to do the first part of your aggregation in BigQuery, get back a Pandas DataFrame, then work with the smaller Pandas DataFrame locally. Vertex AI provides a managed Jupyter experience, so you don't need to run notebook servers yourself.

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:

gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:

gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Invoke BigQuery

Open the BigQuery console

  1. In the Google Cloud Console, select Navigation menu > BigQuery.

The Welcome to BigQuery in the Cloud Console message box opens. This message box provides a link to the quickstart guide and the release notes.

  1. Click Done.

The BigQuery console opens.

  1. In the Query Editor enter the following query:

SELECT plurality, COUNT(1) AS num_babies, AVG(weight_pounds) AS ave_weight FROM `bigquery-public-data.samples.natality` WHERE year > 2000 AND year < 2005 GROUP BY plurality
  1. Now click Run.

  2. Review the result. How many triplets were born in the US between 2000 and 2005?

Click Check my progress to verify the objective.

Invoke Bigquery and run a query.

Task 2. Launch Vertex AI Notebooks

  1. In the Cloud console,in the Search field, type "vertex", then click Vertex AI in the results.

  2. Now select a Region that is close to you then click the Enable Vertex AI API button.

  3. From the left menu click on Workbench.

  4. Click the Enable Notebooks API button.

  5. At the top of the Workbench page, click New Notebook > Python 3.

  6. In the pop-up, confirm the name of the notebook. For Region, select us-central1 and for Zone, select a zone within that region.

  7. Leave the remaining fields with their default and click Create.

  8. Click Open JupyterLab. A JupyterLab window will open in a new tab.

Click Check my progress to verify the objective.

Create AI Platform Notebooks instance.

Task 3. Visualize data in Vertex AI

  1. In JupyterLab, start a new notebook by clicking on Notebook > Python 3.

Start by updating to the latest version of the BigQuery Python Client Library.

  1. Enter the following into the first cell of the notebook, then click the Run button at the top of the screen:

!pip install google-cloud-bigquery==1.25.0 !pip install --upgrade google-cloud-bigquery-storage
  1. Restart the kernel by clicking on Restart the kernel.

  2. Next, insert the following code to import the BigQuery Python Client Library and initialize a client. The BigQuery client will be used to send and receive messages from the BigQuery API.

from google.cloud import bigquery client = bigquery.Client()
  1. Run the cell with Shift + Enter.

  2. Add the following into the next cell of the notebook to run a query on the BigQuery natality public dataset:

sql = """ SELECT plurality, COUNT(1) AS count, year FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(plurality) AND plurality > 1 GROUP BY plurality, year ORDER BY count DESC """ df = client.query(sql).to_dataframe() df.head()

This dataset describes all United States births registered from 1969 to 2008. This query returns the annual count of plural births by plurality (2 for twins, 3 for triplets, etc.).

  1. Run the cell with Shift + Enter.

You just ran a query in the cloud! The head of the DataFrame (the first 5 rows) is displayed below the code cell. Full results are available for further analysis in a Pandas DataFrame.

Run a query to get annual count of plural births by plurality
  1. Insert the following code into the next cell to pivot the data and create a stacked bar chart of the count of plural births over time:

pivot_table = df.pivot(index='year', columns='plurality', values='count') pivot_table.plot(kind='bar', stacked=True, figsize=(15,7));

Next, take a look at baby weight by gender.

  1. In the next cell, enter the following, then run the cell:

sql = """ SELECT is_male, AVG(weight_pounds) AS ave_weight FROM `bigquery-public-data.samples.natality` GROUP BY is_male """ df = client.query(sql).to_dataframe() df.plot(x='is_male', y='ave_weight', kind='bar');

Are male babies heavier or lighter than female babies? Does this align with your expectations?

Run a query to get baby weight by gender

For your last visualization, see how the baby's weight fluctuates according to the number of gestation weeks.

  1. Enter the following into the next cell and run it:

sql = """ SELECT gestation_weeks, AVG(weight_pounds) AS ave_weight FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(gestation_weeks) AND gestation_weeks <> 99 GROUP BY gestation_weeks ORDER BY gestation_weeks """ df = client.query(sql).to_dataframe() df.plot(x='gestation_weeks', y='ave_weight', kind='bar'); Note: Because the gestation_weeks field allows null values and stores unknown values as 99, this query excludes records where gestation_weeks is null or 99.

Now you have a chart that shows how the weight of the baby relates to the number of weeks of gestation.

Run a query to get the weight of the baby which relates to the number of weeks of gestation.

Congratulations!

You learned how to launch a Vertex AI notebook, run queries with BigQuery, and create a chart to show your results.

Finish your quest

This self-paced lab is part of the Scientific Data Processing quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest or any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Take your next lab

Continue your quest with Predicting Baby Weight with TensorFlow on Cloud ML Engine, or try below one:

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated October 21, 2022

Lab Last Tested December 8, 2021

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.