Assignment Notes - Python
Assignment Notes - Python
*[Link]
Syed Ali Ameer
C O M M O N ML QUESTIONS
Which customers are most What will sales look like for What patterns do we see in
likely to churn next month? the next 12 months? terms of product cross-selling?
How can we use online When we adjusted tactics Which product is customer X
customer reviews to monitor last month, did we drive any most likely to purchase next?
changes in sentiment? incremental revenue?
QUALITY ASSURANCE
UNIVARIATE PROFILING
MULTIVARIATE PROFILING
MACHINE LEARNING
Quality Assurance (QA) is about preparing & cleaning data prior to analysis. We’ll cover common QA topics
including variable types, empty/missing values, range & count calculations, censored data, etc.
QUALITY ASSURANCE
UNIVARIATE PROFILING
MULTIVARIATE PROFILING
MACHINE LEARNING
Univariate profiling is about exploring individual variables to build an understanding of your data. We’ll cover
common topics like normal distributions, frequency tables, histograms, etc.
QUALITY ASSURANCE
UNIVARIATE PROFILING
MULTIVARIATE PROFILING
MACHINE LEARNING
Multivariate profiling is about understanding relationships between multiple variables. We’ll cover common
tools for exploring categorical & numerical data, including kernel densities, violin & box plots, scatterplots, etc.
QUALITY ASSURANCE
UNIVARIATE PROFILING
MULTIVARIATE PROFILING
MACHINE LEARNING
Machine learning is a natural extension of multivariate profiling, and uses statistical models and methods to
answer questions which are too complex to solve using simple visual analysis or trial-and-error
MACHINE LEARNING
Clustering/Segmentation
Classification Regression Reinforcement Learning
K-Means (Q-learning, deep RL, multi-armed-bandit, etc.)
There are two common use cases for linear regression: prediction and root-cause analysis
The goal of regression is to predict a numeric dependent variable using independent variables
𝒚 Dependent variable (DV) – for regression, this must be numerical (not categorical)!
• This is the variable you’re trying to predict
• The dependent variable is commonly referred to as “Y”, “predicted”, “output”, or “target” variable
• Regression is about understanding how the numerical DV is impacted by, or dependent on, other variables in the model
EXAMPLE: Using marketing and sales data (sample below) to predict revenue for a given month
Social Posts, Competitive Activity, Marketing Spend and Promotion Count are all
independent variables, since they can help us explain, or predict, monthly Revenue
EXAMPLE: Using marketing and sales data (sample below) to predict revenue for a given month
3 11 Medium $15,000 10 $1,112,050 We’ll use records with observed values for
4 22 Medium $705,000 11 $1,582,077 both independent and dependent variables
5 41 High $3,000 3 $1,889,053 to “train” our regression model...
6 5 High $3,500 3 $1,200,089
11 7 High $320,112 8 ??? ...then apply that model to new, unobserved values
containing IVs but no DV
This is what our regression model will predict!
Syed Ali Ameer
Ordinary Least Squares Method (OLS)
Y-intercept X value
(x ,y )
Univariate Linear
Regression y = 𝘢 + βx β
Y value Slope (rise/run) 𝘢
Multiple Linear
Regression • NOTE: Not all relationships are linear (more on that later!)
Linear Relationships
Univariate Linear
Regression
Non-Linear (logarithmic) No Relationship
Multiple Linear
Regression
Non-Linear
Regression
Linear Relationships 50
40
Consider a line that fits
Least Squared Error every single point in the plot
30
This is known as a perfectly
linear relationship
Univariate Linear 20
Regression
10
Multiple Linear
Regression 10 20 30 40 50 60 70 80
Non-Linear
Regression
In this case you can simply calculate the exact value of Y for any given value
of X (no Machine Learning needed, just simple math!)
Linear Relationships 50
40
In the real world, things
Least Squared Error aren’t quite so simple
30
When you add variance, it
means that many different
Univariate Linear 20
lines could potentially fit
Regression
through the plot
10
Multiple Linear
Regression 10 20 30 40 50 60 70 80
Non-Linear
Regression
To find the equation of the line with the best possible fit, we can use a
technique known as least squared error or “least squares”
• Now square each of those residuals, add them all up, and adjust your line until
you’ve minimized that sum; this is how least squares works!
Univariate Linear
Regression
Linear Relationships 50
X Y (actual) Y (line) Error Sq. Error
10 10 15 5 25
40 20 25 20 -5 25
30 20 25 5 25
Least Squared Error
30 35 30 27.5 -2.5 6.25
40 40 30 -10 100
50 15 35 20 400
Univariate Linear 20
60 40 40 0 0
Regression
65 30 42.5 12.5 156.25
10
70 50 45 -5 25
50 10 100
Multiple Linear 80 40
Regression 10 20 30 40 50 60 70 80
Non-Linear
Regression STEP 1: Plot each data point on a scatterplot, and record the X and Y values
y = 10 + 0.5x
Linear Relationships 50
X Y (actual) Y (line) Error Sq. Error
10 10 15 5 25
40 20 25 20 -5 25
30 20 25 5 25
Least Squared Error
30 35 30 27.5 -2.5 6.25
40 40 30 -10 100
50 15 35 20 400
Univariate Linear 20
60 40 40 0 0
Regression
65 30 42.5 12.5 156.25
10
70 50 45 -5 25
50 10 100
Multiple Linear 80 40
Regression 10 20 30 40 50 60 70 80
Non-Linear
Regression STEP 2: Draw a straight line through the points in the scatterplot, and
calculate the Y values derived by your linear equation
y = 10 + 0.5x
Linear Relationships 50
X Y (actual) Y (line) Error Sq. Error
10 10 15 5 25
40 20 25 20 -5 25
30 20 25 5 25
Least Squared Error
30 35 30 27.5 -2.5 6.25
40 40 30 -10 100
50 15 35 20 400
Univariate Linear 20
60 40 40 0 0
Regression
65 30 42.5 12.5 156.25
10
70 50 45 -5 25
10 100
Multiple Linear 80 40 50
Regression 10 20 30 40 50 60 70 80
Non-Linear
Regression STEP 3: For each value of X, calculate the error (or residual) by comparing
the actual Y value against the Y value produced by your linear equation
y = 10 + 0.5x
Linear Relationships 50
X Y (actual) Y (line) Error Sq. Error
10 10 15 5 25
40 20 25 20 -5 25
30 20 25 5 25
Least Squared Error
30 35 30 27.5 -2.5 6.25
40 40 30 -10 100
50 15 35 20 400
Univariate Linear 20
60 40 40 0 0
Regression
65 30 42.5 12.5 156.25
10
70 50 45 -5 25
100
Multiple Linear 80 40 50 10
Regression
=
862.5
10 20 30 40 50 60 70 80
SUM OF SQUARED ERROR:
Non-Linear STEP 4: Square each individual residual and add them up to determine the
Regression
sum of squared error (SSE)
• This defines exactly how well your line “fits” the plot (or in other words, how well
the linear equation describes the relationship between X and Y)
Syed Ali Ameer
LEAST SQUARED ERROR
y = 12 + 0.4x
Linear Relationships 50
X Y (actual) Y (line) Error Sq. Error
10 10 16 6 36
40 20 25 20 -5 25
30 20 24 4 16
Least Squared Error
30 35 30 26 -4 16
40 40 28 -12 144
50 15 32 17 289
Univariate Linear 20
60 40 36 -4 16
Regression
65 30 38 8 64
10
70 50 40 -10 100
Multiple Linear 80 40 44 4 16
Regression
=
10 20 30 40 50 60
722
70 80
SUM OF SQUARED ERROR:
Non-Linear STEP 5: Plot a new line, repeat Steps 1-4, and continue the process until
Regression
you’ve found the line that minimizes the sum of squared error
• This is where Machine Learning comes in; human trial-and-error is completely
impractical, but machines can find an optimal linear equation in seconds
Syed Ali Ameer
UNIVARIATE LINEAR REGRESSION
Coefficient/parameter
Univariate Linear
Dependent variable (DV) (sensitivity of Y to X)
Regression This is just the equation of
y =𝘢 + βx + 𝜀 Error/residual a line, plus an error term
Multiple Linear
Y-intercept Independent variable (IV)
Regression
Non-Linear
Regression
Simple linear regression is rarely used on its own; think of it as a primer for
understanding more complex topics like non-linear and multiple regression
Linear Relationships Can we use more than one IV to predict the DV?
Multiple Linear DV
Regression
y =𝘢 + β1x1 + β2x2 + β3x3 + … + βnxn + 𝜀 Error/
residual
Non-Linear Y-intercept
Regression Instead of just 1 IV, we have a whole set of independent variables
(and associated coefficients/weights) to help explain our DV
Univariate Linear
Regression
Multiple Linear
Regression
Non-Linear
Regression
Multiple regression can scale well beyond 2 variables, but this is where
visual analysis breaks down (and why we need machine learning!)
Syed Ali Ameer
MULTIPLE LINEAR REGRESSION
EXAMPLE You are preparing to list a new property on AirBnB, and want to estimate
(or predict) an appropriate price using the listing data below
Linear Relationships
Univariate Linear
Regression
Multiple Linear
Regression
Non-Linear
Regression
EXAMPLE You are preparing to list a new property on AirBnB, and want to estimate
(or predict) an appropriate price using the listing data below
Linear Relationships
MODEL 2: Predict price (Y) based on accommodation (X1) and number of bedrooms (X2):
Univariate Linear
Regression Y =52.59 + (15.4*X1) + (5.1*X2)
Multiple Linear MODEL 3: Predict price (Y) based on accommodation (X1), number of bedrooms (X2), and room
Regression type ([Link] (X3), [Link] (X4), [Link] (X5)):
EXAMPLE You are preparing to list a new property on AirBnB, and want to estimate
(or predict) an appropriate price using the listing data below
Linear Relationships
Univariate Linear
Regression
Multiple Linear
Regression
Non-Linear
Regression
Y-intercept
Log-transformed independent variable (IV)
Non-Linear
Regression
All we’re really doing is transforming the data to create linear relationships between each IV and the DV,
then applying a standard linear regression model using those transformed values
EXAMPLE #1 You are predicting Sales (Y) using Marketing Spend (X). As you spend
more on marketing, the impact on sales eventually begins to diminish.
Linear Relationships
Univariate Linear
Regression
Multiple Linear
Regression
The relationship between Sales and Marketing ...but the relationship between Sales and the
Spend is non-linear (logarithmic)... log of Marketing Spend is linear!
Non-Linear
Regression
y = 𝘢 + βx + 𝜀 y = 𝘢 + β*ln(x) + 𝜀
EXAMPLE #2 You are predicting population growth (Y) over time (X) and notice an
increasing rate of growth as the population size increases.
Linear Relationships
Univariate Linear
Regression
Multiple Linear
Regression
The relationship between Time and Population ...but the relationship between Time and the
is non-linear (exponential)... log of Population is linear!
Non-Linear
Regression y = 𝘢 + βx + 𝜀 ln(y) = 𝘢 + βx + 𝜀
NOTE: There are multiple ways to transform variables based on the type of relationship
(log, exponential, cubic, etc.), and multiple techniques to model them (more on that later!)
Syed Ali Ameer
REGRESSION WORKFLOW
Measurement Planning
Adding new, calculated Splitting records into Building regression models Choosing the best
variables (or “features”) to “Training” and “Test” data from Training data and performing model for a given
a data set based on sets, to validate accuracy applying to Test data to prediction, and tuning it to
existing fields and avoid overfitting maximize prediction accuracy prevent drift over time
Social Competitive Marketing Promotion Competitive Competitive Competitive Promotion >10 &
Month ID Revenue LogSpend
Posts Activity Spend Count High Medium Low Social >25
Splitting is the process of partitioning data into separate sets of records for the
purpose of training and testing machine learning models
• As a rule of thumb, ~70-80% of your data will be used for Training (which is what your model
learns from), and ~20-30% will be reserved for Testing (to validate the model’s accuracy)
3 11 Medium $15,000 10 $1,112,050 Using Training data for optimization and Test data
Training for validation ensures that your model can
4 22 Medium $705,000 11 $1,582,077
data accurately predict both known and unknown values,
5 41 High $3,000 3 $1,889,053 which helps to prevent overfitting
6 5 High $3,500 3 $1,200,089
R-Squared measures how well your model explains the variance in the
dependent variable you are predicting
• The higher the R-Squared, the “better” your model predicts variance in the DV
and the more confident you can be in the accuracy of your predictions
y = 12 + 0.4x
50 x y prediction (y–prediction)2 y (y– y )2
10 10 16 36 30 400
40 20 25 20 25 30 25
30 20 24 16 30 100
30 35 30 26 16 30 0
40 40 28 144 30 100
20 50 15 32 289 30 225
60 40 36 16 30 100
10 65 30 38 64 30 0
70 50 40 100 30 400
80 40 44 16 30 100
10 20 30 40 50 60 70 80
=
722 1,450
SSE TSS
ADJUSTED R-SQUARED
A criticism of r-squared is that it will never decrease as new variables are added
Adjusted r-squared corrects this by penalizing new variables added to a model
• This measure has no meaning whatsoever, but it helps as a variable selection tool
R2 increased
but adjusted
R2 didn’t
In this case, the p-value could also tell us to remove this variable
(other times, a variable can be significant and lower adjusted R2)
VARIABLE SELECTION
Variable selection is a critical part of the modeling process that helps reduce
complexity by only including features that help meet the model’s goal
• Do new variables improve model accuracy? (critical for prediction)
• Is each variable statistically significant? (critical for inference)
• Do new variables make the model more challenging to interpret or explain to stakeholders?
Mean error metrics measure how well your regression model fits in in the units of
our target, as opposed to how well it explains variance (like R-Squared)
• The most common are Mean Absolute Error (MAE) and Root Mean Squared Error (RMSE)
• They are used to compare model fit across models (the lower the better!)
Average of the absolute distance Average of the squareddistance Square root of Mean Squared Error,
between actual& predicted values between actual & predicted values to return to the target’sunits(likeMAE)
You can use [Link] to calculate MAE and MSE for your model
• [Link].mean_absolute_error(y_actual, y_predicted)
• [Link].mean_squared_error(y_actual, y_predicted)
• Mean Absolute Error (MAE) is useful if you want to minimize the impact
of outliers on model selection
PRO TIP: In general we recommend considering all of them, since they can be
calculated instantly and each provide helpful context into model performance