Introduction to Machine Learning Concepts
Introduction to Machine Learning Concepts
1
Course Outcomes
• Understand the working of various supervised and
unsupervised machine learning models.
2
Course Material
• Class notes, ppts.
• Text Books
1. Machine Learning, Tom Mitchell, McGraw Hill, 1997.
2. Ethem Alpaydin, Introduction to Machine Learning, PHI,
2016
• Reference Books
1. T. Hastie, R. Tibshirani, J. Friedman. The Elements of
Statistical Learning, 2e, 2008.
2. Christopher Bishop. Pattern Recognition and Machine
Learning. 2e, 2006.
3. Richard O. Duda, Peter E. Hart, David G. Stork. Pattern
classification, Wiley, New York, 2001.
3
Course Guidelines
• Responsibility as a Instructor - Cover all topics.
• Ask me doubts.
• Attendance - 75% and above
• Prepare your notes from class lectures and ppts.
• Refer text books for detailed explanation.
4
Assessment and Marks Distribution
Theory
Lab
Sr. No. Component Marks
1 Regular lab submission 20
Lab evaluation (Immediately after
2 sessional 2) 30
Total 50
5
Assessment and Marks Distribution-
Teachers' Assessment
6
What is Learning?
Learning
The ability to improve behavior based on the experience.
7
What is Learning?
Learning
The ability to improve behavior based on the experience.
8
What is Learning?
9
What is Learning?
10
What is Learning?
11
What is Learning?
Correct 2 3 4
Incorrect 3 2 1
12
What is Machine Learning?
13
Machine Learning
14
Machine Learning to a Layman
15
What is Machine Learning?
Machine Learning
Design of Algorithm that-
• Learn from data or build models using that data
• The learned model can be used to
• Detect patterns/structures/themes/trends etc. in the data
• Make predictions about future data and make decisions
• Modern ML algorithms are heavily “data-driven”
• No need to pre-define and hard-code all the rules (usually
infeasible/impossible anyway).
• The rules are not “static”; can adapt as the ML algorithm
ingests with more and more data.
16
Machine Learning vs Programming
17
When to Use Machine Learning?
• Human expertise is absent
Example: navigating on mars
• Humans are unable to explain their expertise
Example: vision, speech, language
• Requirements and data change over time
Example: Tracking, Biometrics, Personalized
fingerprint recognition
• The problem or the data size is just too large
Example: Web Search
• When not to use it: If you can precisely/mathematically describe
how to solve the task. Just program it.
18
Why Machine Learning?
• Machine Learning term first coined in 1959
• Computer Model based on Neural Network was created in 1943
19
Why Machine Learning?
• Machine Learning term first coined in 1959
• Computer Model based on Neural Network was created in 1943
20
Why Machine Learning?
21
Why Machine Learning?
• Structured Data
• Unstructured Data
• “More than 300 million photos get uploaded per day.
• Every minute there are 510,000 comments posted
and 293,000 statuses updated”
• “Over 2.5 quintillion bytes of data are created
every single day, and it's only going to grow from
there.
• By 2020, it is said that 1.7MB of data has been
created every second for every person on earth”
More than 80% data is unstructured.
22
Why Machine Learning?
Python
Libraries: Pandas, Numpy, Sklearn, Keras
TensorFlow, PyTorch, Theano
23
Why Machine Learning?
Powerful CPUs
GPU
Parallel and Distributed Computing
24
Jargon Difference!
Machine Learning
Data Science
25
Jargon Difference!
26
Types of Learning
• Supervised (inductive) learning: Training data includes desired
outputs.
• Unsupervised learning: Training data does not include desired
outputs, Find hidden/interesting structure in data.
• Semi-supervised learning: Training data includes a few desired
outputs
• Reinforcement learning: the learner interacts with the world via
“actions” and tries to find an optimal policy of behavior with
respect to “rewards” it receives from the environment
27
Types of Learning
28
A Typical Supervised Learning Workflow (for Classification)
29
A Typical Supervised Learning Workflow (for Classification)
30
A Typical Un-supervised Learning Workflow (for Clustering)
31
A Typical Un-supervised Learning Workflow (for Clustering)
Supervised Learning:
Learn a line/curve (the “model”)
using training data consisting of
Input-output pairs (each output is a
real-valued number)
Classification
Clustering
Dimensionality Reduction
Labeled
“dog”
Training
“dog”
Data “dog”
Supervised ML p(class|image)
“cat”
“cat”
“cat”
Unlabeled
Training Unsupervised ML p(image)
Data
36
Machine Learning = Function Approximation
Supervised Learning (“predict y given x ”) can be thought learning a function that maps x to y
Labeled “dog”
Training “dog”
Data “dog”
Supervised : image class
ML
“cat
”
“cat”
“cat”
Unsupervised Learning (“model x ”) can also be thought of as learning a function that maps x to some useful
latent representation of x
Unlabeled
Training
Data latent representation
Unsupervised
ML
: image of image (e.g., cluster
id or compressed
version)
38
Machine Learning helps Computer Vision
39
Machine Learning helps Computer Vision
40
Machine Learning helps NLP
41
Machine Learning helps NLP
42
Machine Learning helps NLP
43
Machine Learning helps NLP- Search and Info Retrieval
44
Machine Learning meets Speech Processing
ML algorithms can learn to translate speech in real time
45
Machine Learning helps Chemistry
ML algorithms can understand properties of molecules and learn to
synthesize new molecules
46
Machine Learning helps Chemistry
ML algorithms can “read” databases of matetials and recreate the
Periodic Table within hours
“Recreated” Periodic Table
47
Machine Learning helps in Biology, E-commerce
48
Inductive Learning
49
Classification Learning
Task T
Input
• A set of instances d1, d2, ...., dn
• An instance has a set of features
• We can represent an instance as a vector
• d = <x1,x2, x3, ...., xn>
Output
• A set of predictions y1, y2, y3, ...., yc
• One of the fixed set of constant values
• Eg: {+1, -1}
51
Inductive Learning
• Also called as Deterministic Supervised Learning
• In this, first input x, (the verified value) given to a function f, and
the output is f(x).
• Then we can give different set of inputs (raw inputs) to the same
function f, and verify the output f(x).
• By using the outputs we generate (learn) the rules.
52
Inductive Learning
• Inductive learning, also known as discovery learning, is a process
where the learner discovers rules by observing examples.
• We can often work out rules for ourselves by observing
examples. If there is a pattern; then record it.
• We then apply the rule in different situations to see if it works.
• With inductive language learning, tasks are designed specifically
to guide the learner and assist them in discovering a rule.
53
Inductive Learning
• Inductive learning or “Prediction”:
– Given examples of a function (X, F(X))
– Predict function F(X) for new examples X
This is the function which we are trying to learn.
• Classification
F(X) = Discrete
• Regression
F(X) = Continuous
• Probability estimation
F(X) = Probability(X):
Why it is called Inductive learning?
We are given some data and we are trying to do induction to
identify a function which can explain that data.
54
Basic Terminologies
Types of features
1. Categorical - It will have finite number of categories and
classes.
Example
– Gender - Male, Female
– Age group: (0-12) children, (13-19) teenagers, (20-30)
adults, 31-60 working professionals, above 60 senior
citizen,
– Blood group: A, B, AB, O etc
2. Integer Valued
Example: Number of words in a text
Example:
<0.5,2.8,+>
3.0
+
+ + +
-
+ + -
2.0
- -
+ - +
-
- + + - - -
1.0
-
+ + + - -
0.0
2. Polynomial
quadratic function: ax² + bx +c
a,b,c- 3 parameters
3. Complex Function
Note:- We are interested in a function which not only fit the
training data but also works well with future or test data.
59
Basic Terminologies
Representation of Function
• When we talk of representation of these hypothesis (or
functions) then we have two things, one is features and the
other is the function class.
60
Basic Terminologies
Representation
61
Basic Terminologies
Representation
62
Basic Terminologies
Hypothesis:
Function for labeling examples
3.0
Label: + + Label:
+ ? + + -
-
+ + -
2.0
- -
+ ? - +
- ?
- + + - - -
1.0
-
+ + + ?
- -
0.0
64
Hypothesis Space
Hypothesis Space:
Set of legal hypotheses
3.0
+
+ + +
-
+ + -
2.0
- -
+ - +
-
- + + - - -
1.0
-
+ + + - -
0.0
66
Hypothesis Space
If there are 2 Boolean input features then there are 22 possible instances.
If there are 3 Boolean input features then there are 23 possible instances.
If there are n Boolean input features then there are 2𝑛 possible instances.
If there are 2 Boolean input features then there are 24 possible Boolean
functions
If there are 3 Boolean input features then there are 28 possible Boolean
functions.
67
Inductive Learning In General
Inducing a general function from training examples.
Constructs a hypothesis h to agree with all the training
examples
A hypothesis is consistent if it agrees (works will) with all
training examples.
A hypothesis is said to be generalized if it correctly predicts the
value of y for new examples.
Example Applications:
• Disease diagnosis
x: Properties of patient (e.g., symptoms, lab test results)
f(x): Predict disease
• Automated steering
x: Bitmap picture of road in front of car
f(x): Degrees to turn the steering wheel
• Credit risk assessment
x: Customer credit history and proposed purchase
f(x): Approve purchase or not 69
70
Learning = Representation + Evaluation +
Optimization
• Combinations of just three elements
Representation Evaluation Optimization
Instances Accuracy Greedy search
Hyperplanes Precision/Recall Branch & bound
Decision trees Squared error Gradient descent
Sets of rules Likelihood Quasi-Newton
Neural networks Posterior prob. Linear progr.
Graphical models Margin Quadratic progr.
Etc. Etc. Etc.
71
Inductive BIAS
As we can see that hypothesis space is very large. It is not possible to
look at every hypothesis individually to choose the best hypothesis.
So we put some restrictions on hypothesis.
If we restrict the hypothesis, it reflects a bias of the learning
algorithm
73
Generalization & Error
Bias
This is the error introduced due to simplifying assumptions
made by a model
Simplified assumptions limit the model's capacity to learn.
Low Bias
Suggests less assumptions about the form of the target
function.
High Bias
Suggests more assumptions about the form of the target
function.
74
Generalization & Error
Variance
Variance tells that how much a random variable is different
from its expected value.
If the machine learning model performs well with the training
dataset, but does not perform well with the test dataset, then
variance occurs.
Low variance.
Suggests small change to the estimated models with Changes
to the training dataset.
High variance.
Suggests large changes, to the estimated models with Changes
to the training dataset.
75
Bias Variance Trade-off
Test
Train Data
Test Data
76
Bias Variance Trade-off
Complex Model
No error on training data
What about test set?
Test Data
77
Bias Variance Trade-off
Complex Model
No error on training data
Test Data
78
Bias Variance Trade-off
Complex Model
No error on training data
Test Data
79
Bias Variance Trade-off
80
Bias Variance Trade-off
Simple Model
More error on training data
What about test set?
Test Data
81
Bias Variance Trade-off
Simple Model
More error on training data
What about test set?
Test Data
82
Bias Variance Trade-off
Simple Model
More error on training data
What about test set?
Test Data
83
Bias Variance Trade-off
84
Bias Variance Trade-off
85
Bias Variance Trade-off
High Low
Train Error
High Bias Low Bias
High Low
Test Error
High Variance Low Bias
Train Data
Test Data
86
Over-fitting
• Over-fitting & under-fitting are the two main errors/problems in
the machine learning model, which cause poor performance in
Machine Learning.
• Over-fitting occurs when the model fits more data than required,
and it tries to capture each and every data point fed to it.
Hence it starts capturing noise and inaccurate data from the
dataset, which degrades the performance of the model.
• An over-fitted model doesn't perform accurately with the
test/unseen dataset and can’t generalize well.
• An over-fitted model is said to have low bias and high variance.
87
How to avoid Overfitting
• Using cross-validation
• Using Regularization techniques
• Implementing Ensemble Techniques.
• Picking a less parameterized/complex model
• Training the model with sufficient data
• Removing features
• Early stopping the training
88
Under-fitting
• Model cannot create a mapping between the input and the target
variable
• Under-observing the features leads to a higher error in the
training and unseen data samples.
• Under-fitting becomes obvious when the model is too simple and
cannot create a relationship between the input and the output.
89
How to avoid Under-fitting
90
91
Over-fitting
Over-fitting during training
Model
error Error on
new data
Training error
Number of iterations
92
Regularization and Over-fitting
Adding a regularizer:
Model
error Without regularizer
With regularizer
Number of iterations
93
Cross-Validation
• Cross-validation involves partitioning your data into
distinct training and test subsets.
94
K-fold Cross-Validation
• To get more accurate estimates of performance you
can do this k times.
• Break the data into k equal-sized subsets Ai
• For each i in 1,…,k do:
– Train a model on all the other folds A1,…, Ai-1, Ai+1,…, Ak
– Test the model on Ai
• Compute the average performance of the k runs
95
5-fold Cross-Validation
96
Occam’s Razer
97
Learning as a search
98
Supervised Learning
Classification Vs. Regression
99
Training Eg. or Input Features Output
Instance
X1 X2 X3 . . Xn Y
I1 a1 a2 a3 . . an Y1
I2 b1 b2 b3 . . bn Y2
Classification or
I3 c1 c2 c3 . . cn Y3 Regression ??
.
.
.
Im P1 P2 P3 . . Pn Ym
Test Input Z1 Z2 Z3 . . Zn ??
Model has to
predict it.
100
Supervised Learning-
For each input x, the desired output y is given. Here y is the label.
101
Classification
• Classification is a process of categorizing a given set of data into classes.
• It can be performed on both structured or unstructured data.
• The process starts with predicting the class of given data points. The classes are often
referred to as target, label or categories.
102
Classification Example:-
You are given with the collection of emails, determine the spam
or non-spam email from it.
103
Regression
• A technique for determining the statistical relationship between two or more variables
where a change in a dependent variable is associated with, and depends on, a change
in one or more independent variables.
• A regression problem is used when the output variable is a real or continuous value,
such as "Salary" or "weight".
104
Regression Example –
• Sales of a product can be predicted by using the relationship
between sales volume and amount of advertising.
• The performance of an employee can be predicted by using
the relationship between performance and aptitude tests.
• The size of a child’s vocabulary can be predicted by using the
relationship between the vocabulary size, the child’s age and
the parents’ educational input.
105
Regression Example – Estimate the price of the house
from the given data.
106
Regression Example – Estimate the price of the house
from the given data.
107
Regression Example – Estimate the price of the house
from the given data.
109
Regression Example – Estimate the price of the house
from the given data.
110
Regression Example – Estimate the price of the house
from the given data.
111
Regression Analysis
112
Dependent and Independent Variable
• Independent variables are considered as an input to a system
and may take on different values freely.
• Dependent variables are those values that change as a
consequence of changes in other values in the system.
• Independent variable is also called as predictor or
explanatory variable and is denoted by X
• Dependent variable is also called as response variable and is
denoted by Y.
113
Linear Regression
• The Simplest mathematical relationship between two
variables x and y is a linear relationship
• In a cause and effect relationship, the independent variable is
cause, and the dependent variable is the effect.
• Least squares linear regression is a method for predicting the
value of a dependent variable Y, based on the value of an
independent variable X.
114
Linear Regression
Height(cm) Weight(KG)
120 45.0
127 51.8
140 58.4
134 55.8
179 86.2
122 44.9
166 68.1
149 52.0
180 95.3
171 73.5
155 61.1
178 89.8
115
Linear Regression
116
The first order linear model
117
Slope & Intercept
Slope:
The slope of a line is the change in y for a one unit increase
in x.
Y-intercept:
It is the height at which the line crosses the vertical axis and
can be obtained by setting x = 0 in the below equation
y = mx + b
118
Error Variable
The inclusion of the random error term allows (x,y) to fall either
above the true regression line (When E > 0) or below the line
(When E < 0)
119
Basis Linear Regression Logistic Regression
Core concept The data is modeled using a It models the probability
straight line of a certain class or event
existing such as yes or no,
win or lose, sick or
healthy, and so on
Used For Continuous variable Categorical Variable
Output/Predi Value of the variable Probability of occurrence
ction of event
Evaluation Measured by loss, R squared, Accuracy, Precision,
Measures Adjusted R Squared. Recall, F1 Score, ROC
curve, Confusion Matrix,
etc.
120
Linear Regression using Least Square Method
121
Linear Regression using Least Square Method
122
Linear Regression using Least Square Method
123
Linear Regression using Least Square Method
124
Linear Regression using Least Square Method
(𝒙 − 𝒙) 𝒚 − 𝒚
𝒎= 𝟐
𝒙−𝒙
125
Linear Regression using Least Square Method
126
Linear Regression using Least Square Method
127
Linear Regression using Least Square Method
128
Linear Regression using Least Square Method
129
Linear Regression using Least Square Method
130
Linear Regression using Least Square Method
(𝒙 − 𝒙) 𝒚 − 𝒚 𝟔
𝒎= 𝟐
= = 𝟎. 𝟔
𝒙−𝒙 𝟏𝟎
132
R-Squared (𝐑𝟐 )
• It is used to determine how
well the regression line fits the
data,
• It measures the proportion of
variance in the dependent
variable (y) that is explained
by the independent variables
(x) in a model.
133
R-Squared (𝐑𝟐 )
• It ranges from 0 to 1, where a higher value indicates a better fit of
the model to the data.
• If R-Squared value is 1 means the model perfectly fits the data,
while an R-Squared value is 0 means the model explains none of
the variability in the data.
• 𝐑𝟐 will always be a positive number.
134
R-Squared (𝐑𝟐 )
135
R-Squared (𝐑𝟐 )
136
R-Squared (𝐑𝟐 )
(Sum of squared distances between the actual and predicted Y values)
𝐑𝟐 = 𝟏 −
(Sum of squared distances between the actual Y values and their mean)
𝒚−𝒚 𝟐
𝐑𝟐 = 𝟏 − 𝟐
𝒚−𝒚
137
R-Squared (𝐑𝟐 )
x y 𝒚 𝐲−𝒚 𝐲−𝒚 𝟐 𝐲−𝒚 𝐲−𝒚 𝟐
1 2
2 4
3 5
4 4
5 5
Mean 4
Given,
Regression line equation 𝒚 = mx + b
m = 0.6, b = 2.2
138
R-Squared (𝐑𝟐 )
x y 𝒚 𝐲−𝒚 𝐲−𝒚 𝟐 𝐲−𝒚 𝐲−𝒚 𝟐
𝒚−𝒚 𝟐 𝟐.𝟒
𝑹𝟐 =𝟏− 𝟐 =𝟏− = 0.6
𝒚−𝒚 𝟔
139
R-Squared (𝐑𝟐 )
140
R-Squared (𝐑𝟐 )
141
R-Squared (𝐑𝟐 )
142
R-Squared (𝐑𝟐 )
143
R-Squared (𝐑𝟐 )
144
Standard Error of Estimate (SEE)
• The standard error of the
estimate is a measure of the
variability of the predicted
values around the true
regression line.
• We calculate the distance
between actual and the
estimated/predicted values
which is called as the Error.
• Therefore our task is to
minimize this error.
145
Standard Error of Estimate (SEE)
𝒚−𝒚 𝟐
𝑺𝑬𝑬 =
𝒏 − (𝒌 + 𝟏)
146
Standard Error of Estimate (SEE)
Given,
n = 5, k= 1
147
SEE Vs 𝐑𝟐
SEE and R-squared are two different measures used in regression
analysis:
• SEE: It is a measure of the variability of the predicted values
around the true regression line. It provides an indication of the
accuracy of the prediction.
• R-squared: It is a statistic that measures the proportion of
variation in the dependent variable that can be explained by
the independent variables. It ranges from 0 to 1.
In summary, the SEE measures the accuracy of the predictions,
while R-squared measures the goodness of fit of the model to
the data.
148
SEE Vs 𝐑𝟐
149
Types of Regression
Univariate and Multivariate regression are two types of regression
analysis used in statistics:
• Univariate Regression: It is a type of regression analysis that
involves only one independent variable and one dependent
variable.
• Multivariate Regression: It is a type of regression analysis that
involves multiple independent variables and one dependent
variable.
150
LR Exercise 1
Q. Study the relationship between the monthly sales and the
advertising costs surveyed for different stores as given below.
Find the equation of the straight line that fits the data best.
Determine the R-squared value.
Store Sales (units) Advertising Cost
1 368000 1700
2 340000 1500
3 665000 2800
4 954000 5000
5 331000 1300
6 556000 2200
7 376000 1300 151
LR Exercise 2
Car age in Price in
Q. Examine the relationship between years Lakhs
the age and price for used cars sold in 4 6.3
the last year by a car dealership
4 5.8
company. Find the equation of the
5 5.7
straight line that fits the data best.
5 4.5
Determine the R-squared value.
7 4.5
7 4.2
8 4.1
9 3.1
10 2.1
11 2.5
12 2.2 152
Other Evaluation Measures
Several evaluation measures are commonly used to assess the
performance of a linear regression model.
153
Error Calculation in Linear Regression
1. Mean Absolute Error (MAE):
It is the simplest regression error metric to understand, it can
be calculated as below:
|𝒚 − 𝒚|
𝑴𝑨𝑬 =
𝒏
154
Error Calculation in Linear Regression
2. Mean Square Error (MSE):
The mean square error (MSE) is similar to the MAE, but squares the
difference before summing them all instead of using the absolute value.
𝒚−𝒚 𝟐
𝑴𝑺𝑬 =
𝒏
155
Error Calculation in Linear Regression
156
Gradient Descent in LR
157
Gradient Descent in LR
xi are features
b, mi are model parameters or coefficient
y is target variable
158
Gradient Descent in LR
Depending on the values of m and b, multiple possible lines can be
possible.
• Error
e = actual − predicted
e=y −𝑦
160
The Cost Function of Linear Regression
• Cost function measures how a machine learning model performs.
• Cost function is the calculation of the error between predicted
values and actual values, represented as a single real number.
• Cost function of a linear regression is mean square error.
𝒚𝒊 −𝒚𝒊 𝟐
• Cost Function 𝐉 =
𝒏
After expanding 𝒚 = b + mx in above equation we get
𝒃+𝒎𝒊 𝒙𝒊 −𝒚𝒊 𝟐
𝑱=
𝒏
• Therefore the best fitting model would be the one which
minimizes the value of cost function.
161
How to minimize the Cost Function?
• We have established the fact that all the straight lines are just
different combination of model parameters b & m.
• Cost Function is the function of parameters b & m.
• Therefore by changing the values of b & m we can change the cost
function.
• We will keep changing the values of b & m till we find a
combination where cost function is minimized.
• To find the best combination we use Gradient Descent
Algorithm.
162
Gradient Descent in LR
163
Gradient Descent in LR
164
Gradient Descent in LR
165
Gradient Descent in LR
166
Gradient Descent in LR
167
Gradient Descent in LR
168
Gradient Descent in LR
169
Gradient Descent in LR
Steps
1. Calculate slope at the current value of parameter b & m separately
2. Take step α and update new parameters.
3. Calculate the cost function J with new (b & m) values.
170
Multivariate Linear Regression
171
Multivariate Linear Regression
172
Multivariate Linear Regression
173
Multivariate Linear Regression
Here,
174
How to use Multivariate Regression Analysis?
The processes involved in multivariate regression analysis include
the selection of features, engineering the features, feature
normalization, selection loss functions, hypothesis analysis, and
creating a regression model.
1. Selection of features:
It is the most important step in multivariate regression. Also known
as variable selection, this process involves selecting viable variables
to build efficient models.
175
Feature Elimination
176
How to use Multivariate Regression Analysis?
2. Feature Normalization: This involves feature scaling to maintain
streamlined distribution and data ratios. This helps in better data analysis.
The value of all the features can be changed according to the requirement.
3. Selecting Loss function and hypothesis: The loss function is used for
predicting errors. The loss function comes into play when the hypothesis
prediction changes from the actual figures. Here, the hypothesis represents
the value predicted from the feature or variable.
177
How to use Multivariate Regression Analysis?
5. Reducing the loss function: The loss function is minimized by
generating an algorithm specifically for loss minimization on the
dataset which in turn facilitates the alteration of hypothesis parameters.
Gradient descent is the most commonly used algorithm for loss
minimization.
178
Assumptions in the Multivariate Regression Model
179
Advantages of Multivariate Regression
180
Disadvantages of Multivariate Regression
181