Checkpoints
Create Cloud Dataproc cluster
/ 50
Create Bayes Classification model
/ 50
Bayes Classifier on Dataproc
GSP272
Overview
In this lab, you explore how to create a two-variable Bayesian model to look at whether to cancel a meeting based on the likely arrival delay of a flight. You quantize using two variables, create a conditional probability lookup table, and examine the on-time arrival percentage in each bin. You carry out the quantization using histogram equalization and on-time arrival percentage computations in Spark.
Dataproc is a managed Spark and Hadoop service that lets you take advantage of open source data tools for batch processing, querying, streaming, and machine learning. Dataproc automation helps you create clusters quickly, manage them easily, and save money by turning clusters off when you don't need them. With less time and money spent on administration, you can focus on your jobs and your data.
This lab uses a set of code samples and scripts developed for Data Science on the Google Cloud Platform, 2nd Edition from O'Reilly Media, Inc.
What you'll learn
In this lab, you'll use Dataproc to do the following:
-
Create a Dataproc cluster
-
Quantization using Spark SQL
-
Create a Bayes classification model
-
Evaluate the model
Setup and requirements
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).
- Time to complete the lab---remember, once you start, you cannot pause a lab.
How to start your lab and sign in to the Google Cloud Console
-
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
-
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. -
If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.
-
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. -
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.
Task 1. Create a Dataproc cluster
In this section you create a Dataproc cluster on which you run the Spark scripts.
-
In the Cloud Console, on the Navigation menu (
), click Compute Engine > VM instances.
-
Click the SSH button inline with
startup-vm
VM to launch a terminal and connect. -
Click
Connect
to confirm the VM launch. -
In the terminal window, run the following command on
startup-vm
to clone thedata-science-on-gcp
repository, and navigate to the directory06_dataproc
:
- Set the project and bucket variables using the following code:
- Before using the file
create_cluster.sh
to create the Dataproc cluster, view the file using thecat
command:
- Create a Dataproc cluster to run jobs on, specifying the name of your bucket and the region that the bucket is in.
Task 2. Quantization using Spark SQL
You can use one variable in your dataset departure delay
to make predictions of the arrival delay of a flight. However, a second variable would make predictions more accurate. As the longer the flight, the more likely that small delays in departure can be made up in the air, the second variable would be the distance to be traveled
.
The statistical model you build in this lab uses two variables — the departure delay
and the distance to be traveled
.
JupyterLab on Dataproc
The Jupyter notebook provides a Python kernel to run Spark code and a PySpark kernel. The Jupyter component in Dataproc is a Web-based notebook for interactive data analytics and supports the JupyterLab Web UI. Jupyter notebooks are widely used for exploratory data analysis and building machine learning models as they allow you to interactively run your code and immediately see your results.
As developing the Bayesian classification from scratch requires being able to interactively carry out development, you use Jupyter notebooks for this lab.
To launch notebook:
-
In the Cloud Console, on the Navigation menu, click Dataproc.
-
In the Cluster list, click on the cluster name to view cluster details.
-
Click the Web Interfaces tab and then click
JupyterLab
. -
In the Launcher dialog, click the
Python 3
tile under Notebook.
Set up environment variables
In this section you set up environment variables (for example, PROJECT
, BUCKET
and REGION
) inside the notebook session. With this notebook you interact with the Dataproc cluster created in Task 1.
- Set up
PROJECT
,BUCKET
andREGION
using the following command in the notebook cell.
- Run the cell by either pressing
Shift + Enter
, or clicking the triangle on the Notebook top menu toRun selected cells and advance
.
Exploration using BigQuery
- First import the basic data science and Google BigQuery API client library followed by creating a BigQuery client object
bq
:
- Enter the code below in new cell and run the cell:
The query samples the full dataset, pulling in 1/1,000 of the flights_tzcorr
table distance
and departure delay
fields (that lie within reasonable ranges) into a Pandas dataframe.
- Use the seaborn library to draw a "hex" kind of plot using
jointplot
:
The distribution plots at the top and right of the center panel of the graph show how the distance
and departure delay
values are distributed.
Start a Spark session
- Type and run the following code in a new cell to Create a Spark session:
- Read the time-corrected JSON files from the Google cloud storage bucket:
- Employ SQL on the dataframe by creating a temporary view (it is available only within this Spark session):
- Employ SQL to query the
flights
view, for example by using this command:
Restrict to train days
- Create a CSV file of the training days Google BigQuery table and save data to cloud storage bucket:
- Create the
traindays
dataframe from the CSV filetrainday.csv
using the following code:
- Now restrict the
flights
dataframe to contain only training days using an SQL join operation:
- Create a
hexbin
plot using Spark (repeat of what you did in BigQuery, except that you now restrict to train days only):
- Finding thresholds that make the two quantized variables uniformly distributed is straightforward using the approximate quantiles method:
- You can similarly quantize the
departure delay
thresholds into equal boundaries:
Task 3. Bayes classification
You have the quantization thresholds, you now need to determine the recommendation (whether to cancel the meeting) for each bin based on whether 70% of flights in that bin are on time or not.
- Find the flights that belong to the
mth
distance bin andnth
delay bin by slicing the full set of flights:
The ontime fraction is nearly 100% for all the delay bins except the largest value for n. This makes perfect sense because only the last departure delay
bin has any delayed flights.
Here, you get close to the 70% threshold only on the last bin. You have to fix this – one way to do so is to hand-select the departure delay
bins. Because you previously looked at thresholding the departure delay
, you know that the interesting range is between 10 and 20 minutes and that departure delay
s are reported in integer minutes. So, you try delay variables of 10, 11, 12, …, 20 minutes.
- Fine-tune the delay threshold around the decision boundary:
- To find the delay threshold for each distance threshold where the value is closest to the 0.70 decision boundary, run the following code:
If the departure delay
is greater than the threshold corresponding to how far the flight is, you cancel the meeting because you expect the flight to be late.
- Write out the table
bayes
as a CSV file to Google cloud storage bucket:
Task 4. Evaluate the model
To evaluate the model you created, look at the flights data that was not used in creating the model.
- Enter the following code into a new cell and run the cell.
Task 5. Delete the dataproc cluster
You created and evaluated your model. Now clean up by deleting the Dataproc cluster.
- Return to the
startup-vm
terminal and delete the dataproc cluster using the following command: and entery
to continue.
-
Enter Y when prompted to confirm.
Congratulations!
You created a Bayesian model to predict the likely arrival delay of a flight. You did this through an integrated workflow that involved BigQuery and Spark SQL.
Finish your quest
This self-paced lab is part of the Data Science on Google Cloud: Machine Learning quest.A quest is a series of related labs that form a learning path. Completing a 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 and get immediate completion credit if you've taken this lab. See the Google Cloud Skills Boost catalog to see all available quests.
Take your next lab
Continue your Quest with Machine Learning with Spark on Google Cloud Dataproc, or check out these suggestions:
Next steps / Learn more
The source of this lab:
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 August 16, 2022
Lab Last Tested March 31, 2022
Copyright 2023 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.