Data+Science+in+Python+ +Unsupervised+Learning
Data+Science+in+Python+ +Unsupervised+Learning
Unsupervised
Learning
With Expert Data Science Instructor Alice Zhao
This is Part 4 of a 5-Part series designed to take you through several applications of data science
using Python, including data prep & EDA, regression, classification, unsupervised learning & NLP
This is a project-based course for students looking for a practical, hands-on approach to
learning data science and applying unsupervised learning models with Python
Quizzes & Assignments to test and reinforce key concepts, with step-by-step solutions
Interactive demos to keep you engaged and apply your skills throughout the course
Recap the data prep & EDA steps required to apply unsupervised learning
3 Pre-Modeling Data Prep models, including restructuring data, engineering features, and more
THE You’ve just been hired as an Associate Data Scientist for the HR Analytics team at a
SITUATION medium-sized software company that’s trying to increase employee retention
You have access to the company’s employee database, including demographic info,
THE performance history, tenure at the company, attrition, and more
ASSIGNMENT Your task is to use unsupervised learning techniques to define employee
segments and make recommendations to increase retention within each one
We’ll also dive into popular applications: anomaly detection & recommenders
• Anomaly detection and recommender techniques include statistical and supervised learning approaches as
well, but we will be focusing on popular unsupervised learning approaches in this course
In this section we’ll install Anaconda and introduce Jupyter Notebook, a user-friendly
coding environment where we’ll be coding in Python
Launching
Jupyter
Launching
Jupyter
Installing
Anaconda
Launching
Jupyter
1) Once inside the Jupyter interface, create a folder to store your notebooks for the course
Installing
Anaconda
Launching
Jupyter
NOTE: You can rename your folder by clicking “Rename” in the top left corner
2) Open your new coursework folder and launch your first Jupyter notebook!
NOTE: You can rename your notebook by clicking on the title at the top of the screen
NOTE: When you launch a Jupyter notebook, a terminal window may pop up as
well; this is called a notebook server, and it powers the notebook interface
Installing
Anaconda
Launching
Jupyter
In this section we’ll introduce the field of data science, discuss how it compares to
other data fields, and walk through each phase of the data science workflow
Yes! The differences lie in the types of problems you solve, and tools and
Machine Learning
techniques you use to solve them:
Data Science
Workflow
What happened? What’s going to happen?
• Descriptive Analytics • Predictive Analytics
• Data Analysis • Data Mining
• Business Intelligence • Data Science
What is Data
Science?
Machine Learning
Data Science
Workflow What will house prices look like How can I segment my
for the next 12 months? customers?
These are some of the most common machine learning algorithms that data
scientists use in practice
What is Data
Science?
MACHINE LEARNING
Essential Skills
The data science workflow consists of scoping the project, gathering, cleaning
What is Data
and exploring the data, applying models, and sharing insights with end users
Science?
1 2 3 4 5 6
Essential Skills
Machine Learning
Data Science
Workflow
Scoping a Gathering Cleaning Exploring Modeling Sharing
Project Data Data Data Data Insights
This is not a linear process! You’ll likely go back to further gather, clean and explore your data
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
Projects don’t start with data, they start with a clearly defined scope:
Data Science
Workflow • Who are your end users or stakeholders?
• What business problems are you trying to help them solve?
• Is this a supervised or unsupervised learning problem? (do you even need data science?)
• What data do you need for your analysis?
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
A project is only as strong as the underlying data, so gathering the right data is
Data Science essential to set a proper foundation for your analysis
Workflow
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
A popular saying within data science is “garbage in, garbage out”, which means that
Data Science
cleaning data properly is key to producing accurate and reliable results
Workflow
Data cleaning tasks may include: Building models
The flashy part of data science
• Resolving formatting issues
• Correcting data types Cleaning data
• Imputing missing data Less fun, but very important
(Data scientists estimate that around
• Restructuring the data 50-80% of their time is spent here!)
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
Exploratory data analysis (EDA) is all about exploring and understanding the
Data Science data you’re working with before applying models or algorithms
Workflow
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
Modeling data involves structuring and preparing data for specific modeling
Data Science techniques, and applying those models to make predictions or discover patterns
Workflow
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
The final step of the workflow involves summarizing your key findings and sharing
Data Science insights with end users or stakeholders:
Workflow
• Reiterate the problem Even with all the technical work
• Summarize the results of your analysis that’s been done, it’s important to
remember that the focus here is
• Share recommendations and next steps on non-technical solutions
NOTE: Another way to share results is to deploy your model, or put it into production
What is Data
Science?
Essential Skills
1 2 3 4 5 6
Scoping a
Project
Gathering
Data
Cleaning
Data
Exploring
Data
Modeling
Data
Sharing
Insights
Machine Learning
DATA PREP & EDA
Data Science
Workflow UNSUPERVISED LEARNING
Data scientists have both coding and math skills along with domain expertise
• In addition to technical expertise, soft skills like communication, problem-solving, curiosity, creativity, grit,
and Googling prowess round out a data scientist’s skillset
In this section we’ll cover the basics of unsupervised learning, including key concepts,
techniques & applications, and where it can be used within the data science workflow
Unsupervised learning is about finding insights & patterns hidden in the data
• Unlike regression or classification, we don’t care about splitting our data into train / test sets
and making predictions, we just care about understanding the relationships in our data
Unsupervised
Learning
Viola 16 52
Rock 5 19
Piper 10 11
Allegra 17 9
Melody 19 50
Cluster 2
Reed 7 44
Podcast enthusiasts
Viola 16 52
Rock 5 19
Cluster 3
Piper 10 11
Casual listeners
Allegra 17 9
Techniques &
Applications We can clearly segment our
MUSIC STREAMING HOURS customers into three clusters:
Data Science • Music lovers
Workflow • Podcast enthusiasts
• Casual listeners
These are
features
PODCAST LISTENING HOURS
Unsupervised
Learning
Identifying groups (or clusters) of data Reducing the number of columns (or
Data Science points that are similar to one another but dimensions) in a data set while losing as
Workflow distinct from other groups little information as possible
Applications: Applications:
• Clustering / Segmentation • Feature Extraction
• Anomaly Detection • Data Visualization
• Recommenders • Recommenders
Unsupervised
Learning
Identifying rare points in a data set that Suggesting items to users based on their
Data Science deviate significantly from the rest preferences or behaviors
Workflow
Unsupervised
Learning Category Unsupervised Learning Techniques Application
Techniques &
K-Means Clustering
Applications
Clustering / Segmentation
Hierarchical Clustering Anomaly Detection
Data Science Recommenders
Workflow Clustering
DBSCAN (Density-Based Clustering)
Feature Extraction
PCA (Principal Component Analysis)
Data Visualization
1 2 3 4 5 6
Scoping a Gathering Cleaning Exploring Modeling Sharing
Unsupervised
project data data data data insights
Learning
Get your data ready to be Apply an unsupervised Evaluate & tune the model Pick the best results and
Data Science input into a model learning technique using metrics and intuition identify any insights
Workflow
The main differences compared to supervised learning are the lack of data splitting (having
training and test sets) and the focus on evaluation based on intuition (versus mainly metrics)
1 2 3 4 5 6
Scoping a Gathering Cleaning Exploring Modeling Sharing
Unsupervised
project data data data data insights
Learning
Can be used as a machine learning Can be used as a machine learning Can be used as an ML alternative to
Data Science alternative to Outlier Detection alternative to Data Visualization Feature Selection / Engineering
Workflow
• Outlier detection is typically • Data is typically visualized using • Feature selection or engineering
done using statistics or plots two dimensions (x and y-axes) is typically done manually by
removing features or applying
• By using anomaly detection, you • By using PCA or t-SNE, high-
transformations to create them
can catch unusual data points dimensional data can also be
and patterns before applying visualized in two dimensions • By using PCA, multiple fields can
other ML algorithms be mathematically reduced to
fewer fields, which is called
feature extraction
The techniques can be used at multiple steps of the data science workflow
• In addition to using unsupervised learning techniques during the modeling step of the data science workflow, select
techniques can also be used during the data cleaning, exploration, and feature engineering phases
In this section we’ll review the data prep steps required before applying unsupervised
learning algorithms, including making sure the rows and columns are set up properly
These are common data prep steps required to transform your source data into a
format that can be directly input into an unsupervised learning model:
Data Prep Steps
Feature
3 Engineering features for modeling
Engineering
To set the correct row granularity, think about the question you’re trying to
answer and determine what one row (observation) of your table will look like
Data Prep Steps
GOAL Cluster customers based on listening behavior
Row Granularity
Customer Genre # Songs Customer # Pop Songs # Indie Songs # Rock Songs
Reed Rock 5
Row Granularity
Column
Preparation
Feature
Engineering
Now each row represents a customer!
Feature Selection
Feature Scaling
Row Granularity
Column
Preparation
Feature
Engineering
Now each row represents a customer, and
we still have the genre information!
Feature Selection
Key Objectives
NEW MESSAGE
March 4, 2024 1. Read the Excel file into a Pandas DataFrame
From: Cindy Cinema (Lead Data Scientist) 2. Check the number of rows and columns
Subject: Please format data for analysis
3. Determine the row granularity needed
Hi, 4. Apply the correct DataFrame transformation
I hear you’re the new associate data scientist on the team – 5. Save the transformation as a new DataFrame
welcome!
6. Check the number of rows and columns
We’re currently working on a project to segment students
based on their entertainment preferences.
Could you format the data in this spreadsheet so that it’s at Hint: The new DataFrame should have 150 rows
the correct row granularity for student-level analysis?
Thanks!
Cindy
[Link]
After setting the row granularity, you need to prepare your columns for modeling:
Feature Scaling PRO TIP: There are some algorithms that can handle null and non-numeric values, including tree-
based models and some classification models, but it’s still best practice to prepare the data this way
You can identify missing data with the .info() or .isna() methods
Row Granularity
Feature
Engineering
Row Granularity
Column
Preparation
Feature
Engineering
Feature Scaling
PRO TIP: The .dropna() method defaults to dropping rows, but
you can drop columns instead by specifying .dropna(axis=1)
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
What values can we fill in here?
• The median age would remove the impact of outliers
• Experience tells us most customers have 0 followers
Pandas will often read in numeric fields as text (object) data types
You can use pd.to_numeric() to convert them to numeric fields
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Pandas will often read in numeric fields as text (object) data types
You can use pd.to_numeric() to convert them to numeric fields
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Pandas will often read in numeric fields as text (object) data types
You can use pd.to_numeric() to convert them to numeric fields
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
Pandas will often read in date fields as text (object) data types as well
You can use pd.to_datetime() to convert them to datetime fields
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Pandas will often read in date fields as text (object) data types as well
You can use pd.to_datetime() to convert them to datetime fields
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
While a datetime field can’t be input into a model, its components can be extracted
as numeric values and saved as new fields for modeling (more on this next)
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
Even though month and day of week look like numeric values, it’s inaccurate to say that 8>5 (August is better than May).
These values often go through an additional process called binning, which we’ll cover in the feature engineering section.
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
PRO TIP: [Link]() is quite versatile and can also be used to set values other than 1/0 (other
numeric values, text values, etc.), set more than two values, set values for another column, and more
A dummy variable is a field that only contains ones and zeros to represent the
presence (1) or absence (0) of a value, also known as one-hot encoding
Data Prep Steps
• They are used to transform categorical fields into multiple numeric fields
Row Granularity
These dummy variables are numeric
representations of the “Education Level” field
Column
Preparation
Graduate High
Name Age Education Level Name Age Education Level College
School School
Feature
Engineering Aria 25 College Aria 25 College 1 0 0
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
Row Granularity
Feature
Engineering
Feature Selection
Feature Scaling
Key Objectives
NEW MESSAGE
March 5, 2024 1. Find the missing values
From: Cindy Cinema (Lead Data Scientist) 2. Fill in the missing values with zeros
Subject: Clean up columns
3. Create a new column called video_game_lover
Hi again, • Set the value to 1 if a student played more
Thanks for getting the data in the correct format earlier. than 7 hours of videos games each week
• Set the value to 0 otherwise
Can you also help me with some column clean up?
There are some null values that I think make sense to fill in
with zeros, since those are fields that the students left blank.
Can you also create a new column that flags students who
really love video games (those who play over 7 hours a week)?
Thanks!
Feature engineering is the process of creating columns that you think will be
helpful inputs for improving a model (help segment, recommend, etc.)
Data Prep Steps
Row Granularity
This DataFrame:
• Is at the correct row granularity
Column • Contains non-null and numeric values
Preparation • Includes newly engineered features
• Is ready for modeling
Feature
Engineering
Row Granularity
1• Setting the correct row granularity
Column • Feature aggregation: aggregating multiple rows into a single row
Preparation
Feature
Engineering 2• Ensuring each column is non-null and numeric
• Handling missing data: imputing missing values
Feature Selection
• Categorical encoding: turning categorical values into numeric values
Feature Scaling
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
You can group numerical features into bins or discrete categories if it makes
more sense for your analysis
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling
Feature
Engineering
Feature Scaling
1.
1 Anyone can apply an algorithm, but only someone with domain expertise
Data Prep Steps
can engineer relevant features, which is what makes a great model
Row Granularity 2.
2 You want your data to be long, not wide (many rows, few columns), so
remember to:
Column
Preparation • Try to collect as many observations (rows) of data as you can
Feature
• Only select the most meaningful features for modeling
Engineering
3.
3 Once you start modeling, you’re bound to find things you missed during
Feature Selection data prep and will continue to engineer features
Feature Scaling
Key Objectives
NEW MESSAGE
March 6, 2024 1. Create a column called total_entertainment
From: Cindy Cinema (Lead Data Scientist) that sums up all the types of entertainment for
each student
Subject: Engineer new features
2. Create a column called pct_screen that
Hi! calculates the percent of entertainment that’s on
screens (everything except for books) for each
We’d like to add a few features before we begin modeling.
student
Can you create the following:
Feature Scaling
While it’s important to remember these fields, they should
not be included when the data is input into a model
More features does not always mean a better model, so it’s important to select a
subset of the features for modeling
Data Prep Steps
Row Granularity
How do we select the “right” number of features?
• Use your intuition and think about the goal for your analysis – which features would do
Column the best job predicting / segmenting / etc.?
Preparation
• Start simple with perhaps two or three features for your model, then assess the results,
and continue to make the model more complex and assess
Feature
Engineering • Don’t worry about getting this right the first time – modeling is a lot of trial and error!
Feature Selection
There are also feature selection and extraction techniques that use machine learning
– we will be covering some of them in the dimensionality reduction section
Feature Scaling
More features does not always mean a better model, so it’s important to select a
subset of the features for modeling
Data Prep Steps
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
My domain expertise & gut feel is telling me that the best way to differentiate customers is by
their age, the total number of songs they listen to and the types of songs they listen to
Feature Scaling
These three features are what I’ll include in my first round of modeling
Key Objectives
NEW MESSAGE
March 7, 2024 1. Save the name column of the DataFrame as its
From: Cindy Cinema (Lead Data Scientist) own Series for reference
Subject: Narrow down features 2. Save the three new columns you engineered as
its own DataFrame for modeling –
Hi again, video_game_lover, total_entertainment and
pct_screen
We’re almost ready for modeling! Just a few more steps.
Can you save the student name column as its own Series that
we can use to reference later on?
Can you create a final modeling DataFrame that includes only
the three new features that we engineered –
video_game_lover, total_entertainment and pct_screen?
Thanks!
Cindy
Scaling, as the name implies, requires setting all input features on a similar scale
• Scaling is an optional feature engineering step which depends on the ML algorithm
Data Prep Steps
• Common techniques for scaling include normalization and standardization
Row Granularity
Column
Preparation
Feature
Engineering
Feature Selection
Feature Scaling PRO TIP: Many unsupervised learning techniques use distance-based
calculations, which makes scaling a required data prep step before modeling
Row Granularity
Column
Preparation
𝑥 − 𝑥𝑚𝑖𝑛
Feature Scaling 𝑥𝑚𝑎𝑥 − 𝑥𝑚𝑖𝑛
Row Granularity
Column
Preparation
𝑥 − 𝑥𝑚𝑒𝑎𝑛
Feature Scaling 𝑥𝑠𝑡𝑑
Key Objectives
NEW MESSAGE
March 8, 2024 1. Scale the features in the modeling DataFrame so
From: Cindy Cinema (Lead Data Scientist) they all have a mean of 0 and a standard
deviation of 1
Subject: Feature scaling request
2. Save the output as a final DataFrame that’s ready
Hi, I have one final request for you. for modeling
We plan on clustering the data using a distance-based
algorithm, so the data needs to be scaled.
Once you do that, we should be all set with our data prep
steps and ready for modeling.
Both the rows & columns of a DataFrame must be prepared for modeling
• There are several techniques that are commonly used to prepare rows and columns for modeling, including
using .groupby(), .pivot(), .fillna(), [Link]() and pd.get_dummies()
Feature engineering can be the difference between a good and a great model
• There are many techniques for feature engineering, including aggregating values, handling missing data,
categorical encoding, applying calculations, binning data, using proxy variables – and then selecting features
In this section we’ll introduce the fundamentals of clustering and compare three popular
clustering techniques: K-Means Clustering, Hierarchical Clustering, and DBSCAN
Comparing Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Clustering Basics
Data Prep Modeling Tuning Selection
K-Means
Clustering
Get your data ready to be Apply a clustering Evaluate & tune the model Pick the best results and
input into an ML model algorithm using metrics and intuition identify any insights
Hierarchical
Clustering
• Single table, non-null • K-Means Clustering • Metrics (i.e. inertia) • Business objective
and numeric data • Hierarchical • Data visualization • Domain expertise
• Feature engineering, Clustering
DBSCAN • Interpret the results
selection, and scaling • DBSCAN
Comparing
Models
Remember, there’s no “right” answer or single optimization metric when it comes to clustering; the best outputs
are the ones which help you answer the question at hand and make practical, data-driven business decisions
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Comparing
Models Example use cases:
• Identifying customer segments for targeted marketing campaigns
• Clustering store locations based on factors like sales, ratings, size, etc.
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
STEP 3: Relocate each centroid to the mean of its assigned observations, and
reassign each observation to the new closest centroid
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
STEP 3: Relocate each centroid to the mean of its assigned observations, and
reassign each observation to the new closest centroid
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
The “k” number of The number of models to fit Setting a random_state value
DBSCAN
clusters to identify with different initial centroids, guarantees the same results
(default is 8) returning the best result each time the model is fit
(”auto” will fit one model)
Comparing
Models
PRO TIP: It’s typically a good idea to start with 2 clusters and build up from there, comparing the results
Clustering Basics
K-Means
Clustering
Comparing
Models
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
Once the model is fit, you can view the cluster that each row
as been assigned to using the .labels_ attribute
DBSCAN
Comparing
Models
You can visualize the results of a K-Means model using the .labels_ attribute and
data visualizations libraries in Python
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
You can interpret the results of a K-Means model using the .cluster_centers_
attribute and your intuition
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Students in the first cluster spend on average: Students in the second cluster spend on average:
• 4.2 hours reading books • 0.6 hours reading books
Comparing • 4.3 hours watching TV shows • 5.1 hours watching TV shows
Models • 6.3 hours playing video games • 5 hours playing video games
These students consume a good amount of These students don’t read many books, so
each type of content, so we could name them we could name them “non-readers”
“consumers of all types of entertainment”
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Key Objectives
NEW MESSAGE
March 11, 2024
1. Read in the [Link] file
From: Clyde Clusters (Sr. Data Scientist)
2. Prep the data by dropping the name and
Subject: K-Means help
manufacturer columns
Thanks!
Clyde
[Link]
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering Square these distances and sum them to calculate inertia for two clusters (K=2)
Hierarchical
Clustering
DBSCAN
Comparing
Models
K-Means
Clustering
Hierarchical
Clustering
INERTIA
DBSCAN
Comparing
Models
2 3 4 5 6 7 8
NUMBER OF CLUSTERS (K)
K-Means
Clustering
DBSCAN
Comparing
Models
2 3 4 5 6 7 8
NUMBER OF CLUSTERS (K)
K-Means
Clustering
DBSCAN
2 3 4 5 6 7 8
NUMBER OF CLUSTERS (K)
You can plot inertia in Python by fitting K-Means models with different values for
“k”, storing the inertia for each one, and visualizing the results
Clustering Basics
Hierarchical
Clustering
DBSCAN
The “elbow” seems
to be at 3 clusters
Comparing
Models
Key Objectives
NEW MESSAGE
March 12, 2024 1. Write a loop to fit K-Means Clustering models
From: Clyde Clusters (Sr. Data Scientist) with 2 to 15 clusters
Subject: More K-Means help 2. Create a plot with the number of clusters on the
x-axis and the inertia on the y-axis
Hi again!
3. Identify the elbow of the plot
Thanks for sharing the results of your 2-cluster model – they
make a lot of sense, so let’s continue down this path. 4. Fit a K-Means Clustering model on the specific
number of clusters at the elbow
Can you fit 14 K-Means Clustering models, using 2-15
clusters, and plot their inertia values? 5. Interpret the cluster centers using a heat map
Once you find the “elbow”, let me know how many clusters we
should use and what you recommend naming those clusters.
Thanks!
Clyde
Part of the clustering workflow is to go back to various data prep and modeling
steps to tune a model before selecting the best one
Clustering Basics
Data Prep
K-Means • Data cleaning: Removing outliers, etc.
Clustering
• Feature engineering: Creating relevant features, etc.
Hierarchical • Feature selection: More features does not mean a better model!
Clustering
• Scaling: K-Means is a distance-based algorithm, so it’s a good idea to scale the data
DBSCAN
Modeling
• Trying a different number of clusters: If your clusters are very different with each run,
Comparing
Models K-Means with that specific number of clusters may not be the best fit for your data, so try
using a different number of clusters
• Trying other clustering models: K-Means works best when the clusters are mostly
circular in shape, but algorithms like Hierarchical Clustering (up next!) can address this
Key Objectives
NEW MESSAGE
March 13, 2024
1. Remove the ”Fat” column
From: Clyde Clusters (Sr. Data Scientist)
2. Standardize the remaining columns
Subject: K-Means Fine Tuning
3. Repeat the steps from the previous inertia plot
Hi again, assignment
I realized that we could potentially improve our model by a) Write a loop to fit K-Means Clustering models
selecting a subset of the features and scaling them. with 2 to 15 clusters
There is no definitive best model when clustering, but a good model has clusters
that make sense, capture patterns, and help solve the business problem
Clustering Basics
K-Means
Clustering
You can explore the clusters using data-based approaches such as:
• Comparing the cluster assignments for the data set and individual rows of data
Hierarchical
Clustering
• Comparing metrics of the various models – inertia, silhouette score (coming soon!), etc.
• Testing the clustering models on unseen data (more on this at the end of this section!)
DBSCAN
Comparing PRO TIP: Sometimes the exact cluster assignments don’t matter as much as the
Models
actionable recommendations you can make based on the clustering models
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
Model 1 has 3 evenly-sized
clusters, while model 2 has
more specific clusters
DBSCAN
Comparing
Models
The “less screens” and
“entertainment enthusiasts”
groups are quite similar and
could possibly be combined
into a single cluster
Key Objectives
NEW MESSAGE
March 14, 2024
1. Compare two models:
a) Label each row in your original data set with a
From: Clyde Clusters (Sr. Data Scientist)
cluster name from the unstandardized data model
Subject: Final K-Means Model and a cluster name from standardized data model
b) How many cereals fall into each cluster?
Hello, thanks for all your help with modeling so far!
c) Decide on the best model for our client
As a reminder, our original goal was to help our client, Maven
Supermarket, set up cereal displays around their store based 2. Recommend a specific number of displays and
on various niches of cereals. suggest a few cereals that should be shown in
Looking at the models that you built, can you compare them each display
and let me know which clusters make the most sense?
Thanks!
K-Means
Clustering
2 clusters
Hierarchical
Clustering p5
p6
DISTANCE
p2
DBSCAN p3
p1
Comparing p4
Models
p1 p2 p3 p4 p5 p6
Hierarchical
2. Then find the next two closest points or clusters, and group them to a cluster
Clustering
3. Repeat the process of combining the closest pairs of points or clusters until you
eventually end up with one single cluster
DBSCAN
Comparing
This process is visualized using a tree diagram called a dendrogram, which shows
Models the hierarchical relationship between clusters
*This is known as agglomerative or “bottom-up” clustering (vs. divisive or “top-down” clustering, which is much less common)
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering How do you define “closest”?
Hierarchical p5
p6
Clustering
p2
p3
DBSCAN
p1
p4
Comparing
Models
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering How do you define “closest”?
• Most commonly, the
Hierarchical
Clustering
p5
p6 Euclidean distance is used
p2
p3
DBSCAN
p1
p4
Comparing
Models
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering How do you define “closest”?
• Most commonly, the
Hierarchical
Clustering
p5
p6 Euclidean distance is used
p2
p3
• Alternatively, there’s
DBSCAN Manhattan distance
p1
p4
Comparing
Models
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering How do you define “closest”?
• Most commonly, the
Hierarchical
Clustering
p5
p6 Euclidean distance is used
p2
p3
• Alternatively, there’s
DBSCAN Manhattan distance
p1 • And Cosine distance
p4
Comparing
Models
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 1: Find the two closest points, and group them into a cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
Comparing
Models 5 clusters
p1 p2 p3 p4 p5 p6
STEP 2: Find the next two closest points/clusters, and group them together
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
Comparing
Models 5 clusters
p1 p2 p3 p4 p5 p6
STEP 2: Find the next two closest points/clusters, and group them together
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
4 clusters
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
4 clusters
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3 3 clusters
DBSCAN
p1
p4
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical p5
p6
Clustering
p2
p3
DBSCAN
p1
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical p5
Clustering p6 • Single linkage (closest)
p2 Which is
shorter?
p3
DBSCAN
p1
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical p5
Clustering p6 • Single linkage (closest)
p2 Which is
shorter? • Complete linkage (furthest)
p3
DBSCAN
p1
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical p5
Clustering Which average p6 • Single linkage (closest)
p2 is smaller?
• Complete linkage (furthest)
p3
DBSCAN • Average linkage (all pairs)
p1
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical p5
Clustering p6 • Single linkage (closest)
p2
• Complete linkage (furthest)
p3
DBSCAN • Average linkage (all pairs)
p1 • Ward’s method (variance)
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering How do you define distance
between clusters?
Hierarchical Which variances
p5
Clustering changed the least? p6 • Single linkage (closest)
p2
• Complete linkage (furthest)
p3
DBSCAN • Average linkage (all pairs)
p1 • Ward’s method (variance)
p4
Comparing
Models
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3 3 clusters
DBSCAN
p1
p4
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering
2 clusters
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
Comparing
Models
p1 p2 p3 p4 p5 p6
STEP 3: Repeat the process until all points are part of the same cluster
Clustering Basics
K-Means
Clustering
Hierarchical p5
p6
Clustering
DISTANCE
p2
p3
DBSCAN
p1
p4
Comparing
Models
p1 p2 p3 p4 p5 p6
The dendrogram() function within the scipy library in Python allows you to
visualize Hierarchical Clustering clusters
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
K-Means
Clustering
Hierarchical
Clustering
The number of The method used to measure The method used to measure
clusters to identify the distance between points the distance between clusters
DBSCAN (default is 2) (default is “euclidean”) (default is “ward”)
Other distances: Other methods:
• “manhattan” • “single”
Comparing
Models • “cosine” • “complete”
PRO TIP: While you can tune • “precomputed” • “average”
these parameters, the defaults
are by far the most common
K-Means
Clustering
Hierarchical
Clustering
Once the model is fit, you can view the cluster
assignments using the .labels_ attribute
DBSCAN
Comparing
Models
K-Means
Clustering
You also get the relationships between features (tv
& video game hours are more closely related!)
Hierarchical
Clustering
NEW MESSAGE
Key Objectives
March 18, 2024
1. Create a dendrogram using the 5 numeric fields
From: Clyde Clusters (Sr. Data Scientist)
of the cereal data set
Subject: Hierarchical Clustering Help
2. Visually identify the ”best” number of clusters
Hi again! and adjust the color_threshold
Thanks for your help applying K-Means to the cereal data set. 3. Create a dendrogram using the 4 standardized
fields (excluding “Fat”) of the cereal data set
To get another perspective, please create dendrograms for
both the original and standardized cereal data sets and let me 4. Visually identify the ”best” number of clusters
know how many clusters you can visually detect in each! and adjust the color_threshold
Finally, fit a hierarchical model on the “best” results from the 5. Fit a hierarchical clustering model on the “best”
standardized data set, visualize the clusters using a cluster map results from the last step and view the labels
and interpret the clusters.
Thanks!
6. Create a cluster map of the “best” results and
Clyde interpret the clusters
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
Comparing
Models
DBSCAN allows for irregular-shaped clusters and can also identify outliers
*This is a rough summary of the steps – more detailed steps are included at the end of the DBSCAN section
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing
Models
STEP 2: Select a point at random and count the points within its radius
• If it’s greater than or equal to the “min_samples”, then start a cluster, label the point as a
Clustering Basics
core point, and mark the points within its radius as a neighbor
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
3
2
DBSCAN 1
4 5
Comparing
Models
STEP 2: Select a point at random and count the points within its radius
• If it’s greater than or equal to the “min_samples”, then start a cluster, label the point as a
Clustering Basics
core point, and mark the points within its radius as a neighbor
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
3
2
DBSCAN 1
4 5
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s greater than or equal to the “min_samples”, label it as a core point, and mark its neighbors
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
2
3
1
DBSCAN 4 5
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s greater than or equal to the “min_samples”, label it as a core point, and mark its neighbors
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
2
3
1
DBSCAN 4 5
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s less than “min_samples”, but at least one of them is a core point, label it as a border point
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2
Clustering
1
DBSCAN
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s less than “min_samples”, but at least one of them is a core point, label it as a border point
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2
Clustering
1
DBSCAN
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s less than “min_samples”, and none of them is a core point, label it as a noise point
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 1
Clustering
2
DBSCAN
Comparing
Models
STEP 3: Move to a neighbor and count the points within its radius
• If it’s less than “min_samples”, and none of them is a core point, label it as a noise point
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 1
Clustering
2
DBSCAN
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
1
2
DBSCAN 3
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
1
2
DBSCAN 3
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN 1
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN 1
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN 2 3
1 4
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN 2 3
1 4
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN 3
4
2 1
6
Comparing 5
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 6
Hierarchical
Clustering
DBSCAN 3
4
2 1
6
Comparing 5
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
2
4
3
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
2
4
3
Comparing
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
3
2
1
Comparing 4
Models 6
5
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
4
2
1
Comparing 4
Models 6
5
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
2
3
Comparing 1
Models
4
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
2
3
Comparing 1
Models
4
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
3
Comparing 2
Models 4
1
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
3
Comparing 2
Models 4
1
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
4
3
Comparing 5
Models 1
2
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
4
3
Comparing 5
Models 1
2
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
2
1
Comparing 4
Models 3
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
2
1
Comparing 4
Models 3
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing 1
4
Models 3
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing 1
4
Models 3
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing 2
1
Models
STEP 4: Move on to another neighbor and continue this process until all the
points are labeled within the cluster
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing 2
1
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2 3
Clustering 1
6
4
5
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2 3
Clustering 1
6
4
5
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 1
Clustering 3
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 1
Clustering 3
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2
Clustering 3
1
4
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 2
Clustering 3
1
4
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering 3
4
2
1
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering 3
4
2
1
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 4
Clustering 3
1
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical 4
Clustering 3
1
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
2 min_samples = 4
Hierarchical 1
Clustering 3
4
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
2 min_samples = 4
Hierarchical 1
Clustering 3
4
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
1 min_samples = 4
Hierarchical 2
Clustering
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
1 min_samples = 4
Hierarchical 2
Clustering
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing
Models
1
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing
Models
1
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
1
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing
Models
STEP 5: Move on to another random point and repeat the same steps
Clustering Basics
2 clusters
K-Means
Clustering
eps = 0.75
min_samples = 4
Hierarchical
Clustering
DBSCAN
Comparing
Models
4 outliers
Clustering Basics
1. Select a radius (eps) and a minimum number of points (min_samples)
2. Within a scatterplot, select a point at random and count the points within its radius
K-Means • If it’s greater than or equal to the “min_samples”, then start a cluster, label the point as a core point,
Clustering and mark the points within its radius as a neighbor
• If it’s less than the “min_samples”, label the point as a noise point and move to step 5
Hierarchical
Clustering 3. Move to a neighbor and count the points within its radius
• If it’s greater than or equal to the “min_samples”, label it as a core point, and mark its neighbors
DBSCAN • If it’s less than the “min_samples”, but at least one of them is a core point, label it as a border point
• If it’s less than the “min_samples”, and none of them is a core point, label it as a noise point
Comparing 4. Continue with another neighbor until all the points are labeled within the cluster
Models
5. Move on to another random point and repeat the same steps
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering
The radius, or maximum distance Minimum points in the radius
between neighboring points needed to become a core point,
(default is 0.5) including the point itself
DBSCAN
(default is 5)
Comparing
Models
You may have noticed that there is no random_state parameter, even though DBSCAN starts at a random point.
This is because sklearn’s implementation of DBSCAN starts at the first point in the data set and moves on from there.
You could attempt to get different labels by shuffling the data, but DBSCAN’s labels don’t vary as much as K-Mean
Clustering’s labels, so this isn’t as big of an issue.
Clustering Basics
K-Means
Clustering
Hierarchical
Clustering You can view the cluster assignments using the .labels_ attribute
(-1 values represent noise points)
DBSCAN
Comparing
Models There are too many noise
points (-1) here, let’s tweak
eps and min_samples to
mainly see clusters instead
While intuition is a large part of comparing clustering models, you can also use metrics
like silhouette score to help compare models
Clustering Basics
• Scores range from -1 to +1, with higher values meaning data points are highly matched to
their own cluster and poorly matched to other clusters (which is a good thing!)
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models Silhouette score = positive Silhouette score ~ zero Silhouette score = negative
The data point fits well in its cluster The data point is near the boundary The data point doesn't fit well in its
and is distant from other clusters between two clusters own cluster and might belong to a
neighboring cluster
The following formula is used to calculate the silhouette score for each data point:
DBSCAN
1.04
1.08 𝟏. 𝟎𝟒 − 𝟎. 𝟑𝟐 The data point fits
= 𝟎. 𝟔𝟗 well in its cluster!
Comparing 𝟏. 𝟎𝟒
Models
K-Means
Clustering
Hierarchical
Clustering
DBSCAN
The data you fit The labels your Distance calculation used to Size of the random subset of data
the model on model generated calculate the silhouette score used to calculate the score
Comparing
(required) (required) (optional, default is “euclidean”) (optional, default is None)
Models
Key Objectives
NEW MESSAGE
March 19, 2024 1. Loop through multiple “eps” and “min_samples”
From: Clyde Clusters (Sr. Data Scientist) values to fit multiple DBSCAN models
Subject: DBSCAN Help 2. Apply the function on both the original and
standardized datasets
Hi again!
3. Find the highest silhouette score and note down
To get one more perspective, please create DBSCAN models on the “eps” and “min_samples” values
the original and standardized data sets using these ranges:
4. Fit a final DBSCAN model with those “eps” and
• eps: 0.1 to 2, with steps of 0.1 “min_samples” values and review the labels
• min_samples: 2 to 10, with steps of 1
Which combination of these values ends up with the highest
silhouette score?
Thanks again for all your help this week!
Clyde
Models
Clustering Basics
K-Means
K-Means Clustering
Clustering
Hierarchical
Clustering
Hierarchical
Clustering
DBSCAN
Comparing
Models
DBSCAN
Once you’ve fit & interpreted your initial models, the potential next steps are to:
Clustering Basics
1.
1 Compare clustering models
K-Means • Silhouette Score: Higher scores closer to 1 mean that clusters are better defined
Clustering
• Intuition: At the end of the day, the main objective is to answer your business question, so you
want to pick the clusters that make the most sense for you to make decisions
Hierarchical
Clustering
2.
2 Label unseen data
DBSCAN • Data Prep: Before labeling unseen data, you must apply the same transformations you applied
to the original data set (feature scaling, etc.) when creating the clusters
Comparing • K-Means Clustering: The .predict method lets you assign unseen data points to a cluster
Models
• Hierarchical Clustering & DBSCAN: While there is no .predict method for these, you can
label unseen data points by re-fitting the models (you may need to update the parameters)
THE You work as a Data Scientist for Northwind Traders, a wholesale distributor that
SITUATION supplies gourmet food products to restaurants, cafes, and specialty food retailers
You have access to their yearly client report, which includes the channel & region for
THE each client, as well as their total spend by product categories in the last year
ASSIGNMENT Your task is to use clustering techniques to understand the different client segments
so the company can better cater to and support each type
In this section we’ll introduce the concept of anomaly detection and cover two popular
unsupervised learning techniques for finding anomalies: Isolation Forests and DBSCAN
Anomaly Detection • Review where anomaly detection sits within the data
Isolation Forests science workflow
Basics
Isolation Forests
DBSCAN
Comparing
Models
DBSCAN
Comparing
Models
1 2 3 4 5 6
Anomaly
Detection Basics Scoping a Gathering Cleaning Exploring Modeling Sharing
project data data data data insights
Isolation Forests
Anomaly • Statistical analysis: flagging data points more than 3 standard deviations away
Detection Basics
from the mean
Isolation Forests • Data visualization: visually identifying distant points by creating histograms,
scatterplots, or boxplots
DBSCAN
• Supervised learning: if you have information on past anomalies, you can apply
classification algorithms like Random Forests to identify new ones
Comparing
Models • Unsupervised learning: if you have unlabeled data, you need algorithms like
Isolation Forests and DBSCAN
Many machine learning algorithms can be modified for anomaly detection including K-Nearest
Neighbors, One-Class Support Vector Machines, Time Series Analysis, etc.
Anomaly
Detection Basics
Type of Technique Unsupervised Learning Techniques Common Applications
Isolation Forests
K-Means Clustering
Clustering
DBSCAN Hierarchical Clustering Clustering
Techniques
DBSCAN (Density-Based Clustering)
Comparing Anomaly Detection
Models Isolation Forests
Get your data ready to be Apply an algorithm for Evaluate & tune the model Pick the best results and
input into an ML model anomaly detection using plots and intuition identify any insights
DBSCAN
Remember, there’s no “right” answer or single optimization metric when it comes to anomaly detection; the best
outputs are the ones which help you answer the question at hand and make practical, data-driven business decisions
An Isolation Forest detects anomalies by building decision trees that split the
data randomly and measure how quickly specific data points can be isolated
Anomaly
Detection Basics
Isolation Forests
TV Shows
<3.6 >3.6
DBSCAN hours hours
Comparing
Models
Books
<0.7 >0.7
hours hours
An Isolation Forest detects anomalies by building decision trees that split the
data randomly and measure how quickly specific data points can be isolated
Anomaly
Detection Basics Here’s how it works:
1. Randomly select a feature from the data and split the observations using a random threshold
Isolation Forests
• If a value is under the threshold, it goes to one branch; otherwise, it goes to the other
DBSCAN 2. Continue splitting the branches using random features and thresholds, creating a tree
structure, until every data point is isolated or a maximum depth is reached
Comparing 3. Repeat these steps using different features and splits to create multiple trees (aka a forest)
Models
4. Calculate the anomaly score for each observation by averaging the number of splits it took to
isolate (path length) in each tree – the lowest scores are anomalies!
Isolation Forests
Anomaly score =1
DBSCAN
Comparing
Models
depth is reached
Isolation Forests
<5.5 >5.5
hours hours
STEP 3: Repeat using different features and splits to create multiple trees
Anomaly
Detection Basics
Isolation Forests
SPLIT 1 SPLIT 2 SPLIT N
Comparing
Models
STEP 3: Repeat using different features and splits to create multiple trees
Anomaly
Detection Basics
Isolation Forests
SPLIT 1 SPLIT 2 SPLIT N
Comparing
Models
STEP 3: Repeat using different features and splits to create multiple trees
Anomaly
Detection Basics
Isolation Forests
SPLIT 1 SPLIT 2 SPLIT N
Comparing
Models
STEP 3: Repeat using different features and splits to create multiple trees
Anomaly
Detection Basics
Isolation Forests
SPLIT 1 SPLIT 2 SPLIT N
Comparing
Models
STEP 4: Calculate the anomaly score for each observation by averaging the
number of splits it took to isolate (path length) in each tree
Anomaly
Detection Basics TREE 1
ANOMALY SCORE This is for a single data point
Isolation Forests 1
SPLIT 1 SPLIT 2 SPLIT N
TREE 2
Books Books Books ANOMALY SCORE
DBSCAN FINAL
TV Shows TV Shows TV Shows 3 ANOMALY SCORE
1.75
Video Games Video Games Video Games
TREE 3
Comparing ANOMALY SCORE
Models
2
TREE N Since the score is so
ANOMALY SCORE
low, this value is
likely an anomaly!
1
Anomaly
Detection Basics
Isolation Forests
DBSCAN
PRO TIP: Even though there is an option to set the contamination percentage
upfront, you can also decide the number of anomalies after fitting the model
Anomaly
Detection Basics
Isolation Forests
Once the model is fit, you can view the scaled anomaly scores
(-0.5 to 0.5) using the .decision_function()
DBSCAN
Comparing
Models
You can visualize anomalies by using the anomaly flags as the “hue” in a pair plot
Anomaly
Detection Basics
Isolation Forests
DBSCAN
Comparing
Models Visually, this student watches less TV
and reads fewer books than the rest
You can visualize anomalies by using the anomaly flags as the “hue” in a pair plot
Anomaly
Detection Basics
Isolation Forests
DBSCAN
Comparing
Models The student that looked like an
anomaly in two dimensions was not
flagged using Isolation Forests
Instead, the anomalies were the
students that watched a lot of TV
and played a lot of video games
After you view the results of your first Isolation Forest model, you can:
• Tune the model by updating the contamination percent to flag more or fewer anomalies
Anomaly
Detection Basics
• Interpret the results by filtering on the anomaly labels or sorting the anomaly scores
Isolation Forests
DBSCAN
Comparing
Models
Key Objectives
NEW MESSAGE
March 20, 2024 1. Open the tripadvisor_reviews.csv file, remove the
From: Molly Anomaly (Researcher) user_id column and view the range of each rating
Subject: Identify Tourist Anomalies 2. Visualize the data using a seaborn pair plot
Thanks!
Molly
tripadvisor_reviews.csv
Isolation Forests
DBSCAN
Comparing
Models
4 outliers
You can use sklearn’s DBSCAN() to apply the DBSCAN algorithm in Python
Anomaly
Detection Basics
Isolation Forests
DBSCAN
The radius, or maximum distance Minimum points in the radius
between neighboring points needed to become a core point,
Comparing (default is 0.5) including the point itself
Models
(default is 5)
Since DBSCAN is a distance-based algorithm, the data should be scaled before being input into the model.
This is different than Isolation Forests, which is NOT distance-based, so no scaling is needed
You can use sklearn’s DBSCAN() to apply the DBSCAN algorithm in Python
Anomaly
Detection Basics
Isolation Forests
DBSCAN
You can view the cluster assignments using the .labels_ attribute
(-1 values represent noise points)
Comparing
Models
You can visualize anomalies by using the anomaly labels as the “hue” in a pair plot
Anomaly
Detection Basics
Isolation Forests
DBSCAN
Key Objectives
NEW MESSAGE
March 21, 2024 1. Paste the DBSCAN function from the anomaly
From: Molly Anomaly (Researcher) detection demo notebook
Subject: RE: Identify Tourist Anomalies 2. Apply the function on the tourist rating data set
Thanks!
Molly
Each anomaly detection technique has pros and cons to keep in mind:
Anomaly
Detection Basics
DBSCAN
Best for local anomaly detection
✓ Handles complex cluster shapes Computationally intensive
DBSCAN Lets you identify local anomalies based
❌
Comparing
Models
Anomaly
Detection Basics
Used to identify data points that are Used to identify data points that are
DBSCAN similar to one another different from the rest
Although they are different concepts, the common thread is that you’re comparing data points to
determine how similar and different they are from one another.
Unsupervised learning is all about finding relationships in data, and these are two ways to capture that
In this section we’ll introduce the fundamentals of dimensionality reduction and cover
two popular techniques: Principal Component Analysis (PCA) and t-SNE
t-SNE
How is this different
from feature selection?
• Feature selection involves
dropping entire columns
• Dimensionality reduction
involves transforming the
original columns
3 dimensions 2 dimensions
t-SNE
3 dimensions 2 dimensions
Reducing the numbers of dimensions in a data set helps with these issues:
Dimensionality
Reduction
PCA
EDA Supervised Learning Unsupervised Learning
It’s difficult for humans to Predictive models fit on “wide” Data points spread out with
t-SNE visualize data with more than data don’t perform as well as more dimensions, and their
2 or 3 dimensions clearly those fit on “long” data distances become more similar
(curse of dimensionality)
Solution: Solution:
Solution:
• Using dimensionality • By reducing dimensions
reduction, 4+ columns in feature engineering, • By reducing dimensions,
can be reduced to 2 or 3 the data gets “narrower” distance calculations
become more meaningful
1 2 3 4 5 6
Scoping a Gathering Cleaning Exploring Modeling Sharing
Dimensionality project data data data data insights
Reduction
Can be used as a machine learning Can be used for Feature Engineering Can be used as an unsupervised
t-SNE
alternative to Data Visualization when preparing supervised learning learning technique for Recommenders
• Data is typically visualized using • Feature selection or engineering • SVD is a general matrix
two dimensions (x and y-axes) is typically done manually by factorization technique that
removing features or applying encompasses PCA
• By using PCA or t-SNE, high-
transformations to create them
dimensional data can also be • SVD reduces the dimensions of a
visualized in two dimensions • By using PCA, multiple fields can user’s behavior to the most
be mathematically reduced to important so that they can be
fewer fields, which is called better compared with others
feature extraction
We’ll cover SVD in the
Recommenders section
Dimensionality
Reduction
Data Prep Modeling Tuning Selection
PCA
Get your data ready to be Apply a dimensionality Evaluate & tune the model Pick the best results and
input into an ML model reduction technique using metrics and intuition identify any insights
t-SNE
• Single table, non-null • PCA • Explained variance • Business objective
and numeric data • t-SNE • Interpret the results • Domain expertise
• Feature engineering,
• SVD
selection and scaling
Remember that dimensionality reduction is often a step taken before other modeling steps, so in addition to going
through the workflow above, you may need to follow it up with other supervised or unsupervised learning workflows
PCA
t-SNE
y
x x
t-SNE 3. Create another line perpendicular to the first one that captures the most spread, or
variation, in the data– this is the second principal component (PC2)
4. Repeat Step 3 until you have as many principal components as original columns
5. To reduce dimensions, keep a subset of principal components (i.e. PC 1 only)
STEP 1: Create a scatter plot and find the center of the data
Dimensionality
Reduction
PCA
t-SNE
y
STEP 1: Create a scatter plot and find the center of the data
Dimensionality
Reduction
PCA
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA
Start with a
random line
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA d12
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA d12 + d22 + d32 + d42 + d52 + d62 + d72 + d82 = 4.8
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA d12 + d22 + d32 + d42 + d52 + d62 + d72 + d82 = 4.8
Find the line that maximizes
the sum of squared distances
t-SNE
y
Why maximize the distance?
• This guarantees that the
principal component line
captures the most variation
in the data
x
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA d12 + d22 + d32 + d42 + d52 + d62 + d72 + d82 = 9.4
The distance almost doubled!
t-SNE Note that the points are
y more spread out now
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA
t-SNE
y
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA d12 + d22 + d32 + d42 + d52 + d62 + d72 + d82 = 12.2
This is the maximum sum
of squared distances
t-SNE The points are even more
y spread out now
STEP 2: Trace a line through the center that captures the most spread, or
variation, in the data – this is the first principal component (PC 1)
Dimensionality
Reduction
PCA
t-SNE
y
STEP 3: Create another line perpendicular to the first one that captures the
most spread, or variation, in the data – this is PC2
Dimensionality
Reduction
PCA
t-SNE
y
STEP 4: Repeat Step 3 until you have as many PCs as original columns
Dimensionality
Reduction
PCA
We can’t draw another perpendicular line
in a 2-dimensional space, so we’re all set!
t-SNE
y
STEP 5: Transform the data into a new space with the PC 1 line as the x-axis, the
PC2 line as the y-axis, and so on
Dimensionality
Reduction
PCA
t-SNE
y
STEP 5: Transform the data into a new space with the PC 1 line as the x-axis, the
PC2 line as the y-axis, and so on
Dimensionality
Reduction
PCA
t-SNE
y
PCA
t-SNE
y
PCA
t-SNE
y
PCA
t-SNE
y
PCA
t-SNE
PC1
PCA
x PC1
PCA
x x
You can use sklearn’s PCA() to apply the Principal Component Analysis algorithm
Dimensionality
Reduction
PCA
t-SNE
The number of columns you want
to reduce the dataset into
You can use sklearn’s PCA() to apply the Principal Component Analysis algorithm
Dimensionality
Reduction
The explained variance ratio shows how much of the variation from the data is
captured by each principal component
Dimensionality
Reduction • The first component will always capture the most variance, and then it decreases from there
• The sum of the explained variance ratios across all components will be equal to 1
PCA
t-SNE
You can represent 88% of the information
captured in the 3 original columns by only
keeping one principal component
Key Objectives
NEW MESSAGE
March 25, 2024
1. Read in the student grades data set
From: Tim Menschen (Assistant Principal)
Subject: Student Analysis 2. Drop the first column with student_id
3. Center the data
Hello!
4. Fit a PCA model with 2 components
Our guidance counselor would like to understand the types of
students at our school to recommend appropriate colleges. 5. View and interpret the explained variance ratios
I was a data scientist in my past life, and I remember that PCA
helps visualize many dimensions in two dimensional charts.
Could you apply PCA on the attached student grades data set
and let me know if two dimensions are able to capture a decent
amount of variance in the data?
Thanks!
Tim
student_grades.csv
Dimensionality
Reduction
PCA
Each row represents a principal component, and each
column represents a column from the original data set
t-SNE
PC 1: Higher values = more books (0.93) PC 2: Higher values = more TV shows (0.89)
and some more video games (0.34) and some more video games (0.43)
You can use the .transform() method to transform the original observations into
the new dimensional space, which you can then visualize in a scatter plot
Dimensionality
Reduction
PCA
t-SNE
Key Objectives
NEW MESSAGE
March 26, 2024 1. Interpret the components of the PCA model
From: Tim Menschen (Assistant Principal) 2. Plot the students on a scatter plot with the x-axis
Subject: Student Analysis Visualization as PC1 and the y-axis as PC2
Can you plot the students in the two dimensions, explain what
the axes represent, and what you observe visually in the plot?
Remember that feature selection and feature extraction are both ways to
reduce the number of dimensions or columns in a table
Dimensionality
Reduction Feature Selection Feature Extraction
PCA
t-SNE
Remember that feature selection and feature extraction are both ways to
reduce the number of dimensions or columns in a table
Dimensionality
Reduction
PCA
t-SNE
Once you have fit and interpreted a PCA model, the next steps are:
Dimensionality
Data Visualization
Reduction
• If you’re able to distinguish data points visually, you’re all set!
• If it’s difficult to visually distinguish data points:
PCA
• You can vary the inputs, modify the number of dimensions, etc.
• You can try other dimensionality reduction techniques, such as t-SNE (coming up next!)
t-SNE
Modeling
• Once you’ve identified the principal components, they can used be inputs into a machine
learning model
• You’ll need to apply the same PCA transformations to the test data
While PCA is a good technique for reducing dimensions to potentially increase predictive model performance,
one of the main downsides is that the transformed features are difficult to interpret
Dimensionality
Reduction
B R
S
A C Q
Z
PCA D T
U
X
X
t-SNE Q
U
Z
C
D
B
S A
T
t-SNE isn’t concerned with maintaining the absolute distances between the points accurate,
instead it focuses on offering a useful estimate of the relationships between them
t-SNE 3. Calculate the average affinity score for each pair of points
4. Randomly place the data points in a low dimensional space
5. Use the affinity scores between pairs to attract (high affinity) or repulse (low affinity) the points until
they have “stabilized” into their final position
Dimensionality
Reduction
B
PCA
A C
t-SNE
X
Q
U
T S
Dimensionality
Reduction
t-SNE
X
Q
U
T S
Dimensionality
Reduction
D distanceAX = 5.3
t-SNE
X
Q
U
T S
Dimensionality
Reduction
D distanceAX = 5.3
t-SNE
X
Q
U
T S
Dimensionality
Reduction
T S
STEP 2: Use the distances to calculate the affinity score (0-1) for each point with
the rest (high affinity score = high probability of being neighbors)
Dimensionality
Reduction
B
PCA
A C
t-SNE
X
Q
U
T S
STEP 2: Use the distances to calculate the affinity score (0-1) for each point with
the rest (high affinity score = high probability of being neighbors)
Dimensionality
Reduction
STEP 2: Use the distances to calculate the affinity score (0-1) for each point with
the rest (high affinity score = high probability of being neighbors)
Dimensionality
Reduction
STEP 2: Use the distances to calculate the affinity score (0-1) for each point with
the rest (high affinity score = high probability of being neighbors)
Dimensionality
Reduction
STEP 2: Use the distances to calculate the affinity score (0-1) for each point with
the rest (high affinity score = high probability of being neighbors)
Dimensionality
Reduction
STEP 3: Calculate the average affinity score for each pair of points
Dimensionality
Reduction
PCA B
affinityAX = low affinityXA = medium
A C
T S
Dimensionality
Reduction
PCA D
Q
S Z
t-SNE C
R A
B U
T
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA D
Q
S Z
t-SNE C
R A
B U
T
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA D Q
Z
S
t-SNE This attraction and repulsion is done by
C gradient descent on a KL loss function
R
A
X
B
U
T
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA D Q
Z
S
t-SNE
C
R
A
X
B
U
T
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA
Q
D Z
S
t-SNE
R
X A
T U
B
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA
S Q
Z
R
t-SNE D
T
X U
C
A
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA R
S
Q
Z
T
t-SNE
U
X
D
A B
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA R
S
Z Q
T
U
t-SNE X
D
C
B
A
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
PCA S
R
Q
Z
T
U
t-SNE X
C
D
B
A
STEP 5: Use the affinity scores between pairs to attract (high affinity) or repulse
(low affinity) the points until they have “stabilized” into their final position
Dimensionality
Reduction
B
PCA S
R
A C Q
Z
D T
U
t-SNE X
X
Q
U
Z
C
D
B
S A
T
You can use sklearn’s TSNE() to apply the t-SNE algorithm in Python
Dimensionality
Reduction
PCA
t-SNE
The number of columns you want Setting a random_state value
to reduce the dataset into guarantees the same output
(ideally 2 or 3 for visualization) after each run
PRO TIP: Unlike PCA, you don’t need to center the data for t-SNE since the
algorithm is based on pairwise similarities, but like PCA, scaling is recommended
You can use sklearn’s TSNE() to apply the t-SNE algorithm in Python
Dimensionality
Reduction
PCA
t-SNE
Key Objectives
NEW MESSAGE
March 28, 2024 1. Fit a t-SNE model with 2 components
From: Tim Menschen (Assistant Principal) 2. Plot the students on a scatter plot with the x-axis
Subject: RE: Student Analysis Visualization as component 1 and the y-axis as component 2
PCA visualizations are more accurate and interpretable, while t-SNE visualizations
are better at visually separating groups of data into clusters
Dimensionality
Reduction
PCA (Entertainment) t-SNE (Entertainment)
PCA
t-SNE
With t-SNE, the two clusters in the data are clearly displayed
PCA visualizations are more accurate and interpretable, while t-SNE visualizations
are better at visually separating groups of data into clusters
Dimensionality
Reduction
PCA (Cereal) t-SNE (Cereal)
PCA
t-SNE
With t-SNE, the large blob of data is shown as more distinct groups
PCA
t-SNE
PRO TIP: You can use this visualization approach in addition to metrics (inertia plots, silhouette
scores, etc.) and intuition when deciding on the ideal number of clusters when clustering
Key Objectives
NEW MESSAGE
March 29, 2024 1. Fit a K-Means model with 3 clusters
From: Tim Menschen (Assistant Principal) 2. Overlay the 3 clusters onto a t-SNE plot
Subject: RE: Student Analysis Visualization
3. Interpret the cluster centers
Happy Friday!
Can you highlight the clusters in the t-SNE plot using colors?
In this section we’ll introduce the concept of recommenders and cover two common
ways of making recommendations: content-based filtering and collaborative filtering
In addition to using cosine similarity and SVD, there are many other approaches to creating recommenders,
including algorithms like regression, classification, clustering, association rule mining, and more
Content-Based
Filtering EXAMPLE Recommending fruits based on their nutritional profiles
Content-Based
Filtering EXAMPLE Recommending fruits based on their nutritional profiles
Collaborative
Filtering
Peach
Next Steps Banana
cos 𝟔𝟎 = 𝟎. 𝟓
Sugar
Mango
Mangos and limes
are not very similar
Lime
60°
Vitamin C
Content-Based
Filtering EXAMPLE Recommending fruits based on their nutritional profiles
Collaborative
Filtering
Peach
Next Steps Banana
cos 𝟒𝟑 = 𝟎. 𝟕𝟑
Sugar
Mango
Peaches are more similar
to mangos than limes
43° Lime
Vitamin C
Content-Based
Filtering EXAMPLE Recommending fruits based on their nutritional profiles
Collaborative
Filtering
Peach
Next Steps Banana
cos 𝟗 = 𝟎. 𝟗𝟖
Sugar
Mango
Bananas are the most similar
fruit to mangos – we should
Lime recommend them!
9°
Vitamin C
Content-Based
Filtering EXAMPLE Recommending fruits based on their nutritional profiles
Collaborative
Filtering
There are many similarity metrics to
choose from, but cosine similarity is
Peach popular in machine learning because:
Next Steps Banana
• It focuses on direction instead of
magnitude
Sugar
Mango
• It can handle high dimensions
• It works well on sparse data
(data containing many 0 values)
Lime
9°
Vitamin C
Content-Based
Filtering
Collaborative
Filtering
Next Steps
Content-Based
Filtering
Collaborative
Filtering
Next Steps
Content-Based
Filtering
Collaborative
Filtering
Key Objectives
NEW MESSAGE
April 1, 2024 1. Read in the data from the first tab of the
From: Becca Mender (Data Scientist) spreadsheet, which contains genre labels
Subject: Movie Recommender Project 2. Remove the non-genre columns in the data
Thanks!
Becca
Movie_Ratings.xlsx
You may need to pivot your data in Python to structure it as a user-item matrix
Recommenders
Basics
Content-Based
Filtering
Next Steps
Key Objectives
NEW MESSAGE
April 2, 2024 1. Read in the movies, users, and ratings tabs of the
From: Becca Mender (Data Scientist) spreadsheet into three DataFrames
Subject: Collaborative Filtering Data Prep 2. Use .pivot() to restructure the ratings data into a
user-item matrix
Hi again,
Thanks!
Movie_Ratings.xlsx
Pineapple
Pineapple
Collaborative
Banana
Banana
Mango
Mango
Lemon
Lemon
Peach
Peach
Filtering
Lime
Lime
f1 f2 f1 f2
Adam Adam f1 f1
Next Steps
Liz
≈ Liz
x
f2
Σ x
f2
VT
Daisy
X Daisy
U
Bob Bob Both SVD and PCA are matrix
factorization techniques, with PCA often
Hannah Hannah used for data visualization and feature
extraction, and Truncated SVD for
recommenders and other applications
*SVD is the true mathematical model, but we’ll technically be working with Truncated SVD, which is a popular application *Copyright Maven Analytics, LLC
SINGULAR VALUE DECOMPOSITION
Pineapple
Pineapple
Collaborative
Banana
Banana
Mango
Mango
Lemon
Lemon
Peach
Peach
Filtering
Lime
Lime
f1 f2 f1 f2
Adam 1.1 4.3 4.7 1.0 2.4 4.9 Adam 7.5 4.0 f1 42 0 f1 0.42 0.37 0.38 0.37 0.43 0.44
Next Steps
Liz 1.2 4.6 4.5 1.3 2.1 4.8
= Liz 7.5 3.9
x
f2 0 17
x
f2 -0.4 0.41 0.47 -0.4 -0.2 0.33
Daisy 4.8 3.7 4.1 2.2 3.3 2.4 Daisy 8.3 0.1
The V T matrix helps understand the combination of
Bob 2.5 2.9 3.7 4.1 1.8 4.1 Bob 7.7 0.9 items that make up each latent feature
Hannah 4.2 4.1 2.3 3.2 5.0 1.7 Hannah 8.3 -1.4
The U matrix is what’s of interest to us, as it
contains the preferences of every user
*SVD is the true mathematical model, but we’ll technically be working with Truncated SVD, which is a popular application *Copyright Maven Analytics, LLC
SINGULAR VALUE DECOMPOSITION IN PYTHON
You can use sklearn’s TruncatedSVD() function to apply the SVD algorithm
• Use .fit_transform(X) to return the U matrix
Recommenders • Use .singular_values_ to return the importance for each latent feature, or the sigma matrix
Basics
• Use .components_ to return the VT matrix
Content-Based
Filtering
Collaborative
Filtering
Next Steps
You can choose the
number of latent
features to extract
Key Objectives
NEW MESSAGE
April 3, 2024 1. Apply TruncatedSVD to the user-item matrix
From: Becca Mender (Data Scientist) from the last assignment
Subject: Let’s create a recommender! 2. View the user-item matrix and the shape of the
user-item matrix
Hi again,
3. View the U matrix and the shape of the U matrix
Thanks for pulling together the user-item matrix yesterday.
4. View the VT matrix and the shape of the VT
Next, let’s create a recommender! matrix
Can you apply TruncatedSVD to the user-item matrix using 2
components?
Thanks!
Becca
You can use the explained variance ratio to choose the number of components
Recommenders
Basics
Content-Based
Filtering
Collaborative
Filtering
Next Steps
The first two components capture
85% of the variance in the data
Key Objectives
NEW MESSAGE
April 4, 2024 1. Fit a TruncatedSVD model with 500 components
From: Becca Mender (Data Scientist) 2. Plot the cumulative explained variance ratios
Subject: Tuning the recommender
3. Suggest a “good” number of components that
best captures the variance in the data
Hi again,
Using the code from yesterday, can you try applying 4. Fit another TruncatedSVD model with the
TruncatedSVD with 500 components? “good” number of components
Thanks!
Becca
Recommenders
Basics
The model captures 85% of
the variance in the data
Content-Based
Filtering
Collaborative
Filtering STEP 2: Use .transform() to get the latent features for a new user
Next Steps
Recommenders
Basics
How does this work?
• By multiplying the new user’s U
Content-Based matrix with the model’s VT matrix
Filtering
(svd.components_), we get an
approximation of their ratings
Collaborative
Filtering
Next Steps
Key Objectives
NEW MESSAGE
April 5, 2024 1. Open the notebook and take a look at the new
user DataFrame
From: Becca Mender (Data Scientist)
Subject: Recommend movies 2. Transform the user into the latent space using
.transform()
Happy Friday! 3. Reconstruct the user-item matrix for the user
I have one final request for you. Let’s test out our SVD model
using [Link]()
on a new user.
4. Make 10 movie recommendations for the user
In the attached notebook, I’ve included the movie ratings that
a new user provided.
5. Review them to determine if they make sense
Can you generate 10 movie recommendations for her using 6. Optional: Try playing around with the number of
our final SVD model (with 250 components) and see if they components to see the difference in movie
make sense? recommendations
Thanks for all your help this week!
section08_recommenders_assignments.ipynb
Collaborative
2• Evaluate the quality of recommendations
Filtering • A common approach is to deploy your model, see how users react to the
recommendations, and then make tweaks to create a better recommender
Next Steps
3• Deal with the difficulties of recommenders
• Tuning recommenders is an on-going process, and includes difficulties like changes to
items, data sparsity, popularity bias, and the “cold start” problem
THE You’ve just been hired as a Data Scientist for MavenEats, a restaurant review
SITUATION website that suggests restaurants to users based on their past restaurant ratings
You have access to data on each user’s restaurant ratings on the website
THE
Your task is to create a recommender that (1) displays five suggested restaurants on a
ASSIGNMENT user’s homepage and (2) five similar restaurants on each restaurant’s details page
In this section we’ll review the foundations of unsupervised learning covered in the
course, including techniques, applications, and its place in the data science workflow
Unsupervised learning is about finding insights & patterns hidden in the data
• We care about understanding the relationships in unlabeled data, not making predictions
Unsupervised
Learning
Are you trying to predict something?
Techniques &
Applications Yes No
Data Science Use a supervised learning technique Use an unsupervised learning technique
Workflow
Group Reduce
Evaluating the results of
unsupervised learning models
is less about metrics and more
about intuition and fulfilling
the business objective
Unsupervised
Learning Category Unsupervised Learning Techniques Application
Techniques &
K-Means Clustering
Applications
Clustering / Segmentation
Hierarchical Clustering Anomaly Detection
Data Science Recommenders
Workflow Clustering
DBSCAN (Density-Based Clustering)
Feature Extraction
PCA (Principal Component Analysis)
Data Visualization
Unsupervised
1 2 3 4 5 6
Learning
Techniques &
Applications
Data Science
Workflow
Scoping a Gathering Cleaning Exploring Modeling Sharing
Project Data Data Data Data Insights
The techniques can be used at multiple steps of the data science workflow
• In addition to using unsupervised learning techniques during the modeling step of the data science workflow, select
techniques can also be used during the data cleaning, exploration, and feature engineering phases
THE You’ve just been hired as an Associate Data Scientist for the HR Analytics team at a
SITUATION medium-sized software company that’s trying to increase employee retention
You have access to the company’s employee database, including demographic info,
THE performance history, tenure at the company, attrition, and more
ASSIGNMENT Your task is to use unsupervised learning techniques to define employee
segments and make recommendations to increase retention within each one