Module 1 - Machine Learning III
Module 1 - Machine Learning III
IPH2445
Course Notes
Department of Physics
Marian College Kuttikkanam (Autonomous)
• Medical diagnosis
• Weather prediction
• Recommendation systems
• Autonomous vehicles
• Image recognition
• Speech recognition
• Fraud detection
Key Point
A machine learning system learns patterns from data and uses those patterns to
make predictions or decisions.
1
IPH2445: Machine Learning using Python – III Chapter 1
Example
A hospital wants to determine whether a patient has diabetes based on age, blood
sugar level and BMI.
Possible classes:
• Diabetic
• Non-Diabetic
2
IPH2445: Machine Learning using Python – III Chapter 1
• Input features
• Correct output labels
Example
Applications
• Email Spam Detection
• Disease Diagnosis
• Face Recognition
• Credit Approval
• Handwritten Digit Recognition
Applications
• Customer Segmentation
• Market Basket Analysis
• Recommendation Systems
• Anomaly Detection
• Image Compression
3
IPH2445: Machine Learning using Python – III Chapter 1
Examples:
• Disease / No Disease
• Pass / Fail
• Approve / Reject
Examples:
• Animal Classification
• Language Identification
• Fruit Classification
3. Fraud Detection
4
IPH2445: Machine Learning using Python – III Chapter 1
4. Face Recognition
5. Autonomous Vehicles
6. Astronomy and Astrophysics
7. Particle Physics Experiments
1.12 Summary
• Machine learning enables computers to learn from data.
• Classification predicts categories rather than numerical values.
• Supervised learning uses labeled data.
• Unsupervised learning uses unlabeled data.
• Binary classification involves two classes.
• Multiclass classification involves three or more classes.
Descriptive Questions
1. Explain the workflow of a machine learning system.
2. Discuss classification with suitable examples.
3. Compare supervised and unsupervised learning.
4. Explain binary and multiclass classification.
5. Describe applications of classification in science and engineering.
5
IPH2445: Machine Learning using Python – III Chapter 1
Application-Oriented Questions
1. Explain why diabetes prediction is a classification problem.
2. Suggest a suitable learning method for customer segmentation.
3. Design a spam email classifier and identify inputs and outputs.
4. Formulate student pass/fail prediction as a classification problem.
5. Explain why handwritten digit recognition is a multiclass classification task.
2.2 Introduction
In the previous section, classification problems were introduced as tasks that assign data
points to predefined categories. A natural question arises: How can a machine learning
algorithm decide whether an object belongs to one class or another?
One of the most widely used algorithms for solving binary classification problems is
Logistic Regression. Despite its name, Logistic Regression is primarily a classification
algorithm rather than a regression algorithm.
Logistic Regression predicts the probability that a data sample belongs to a particular
class. The predicted probability is then converted into a class label using a decision
threshold.
Typical applications include:
• Disease diagnosis
• Email spam detection
• Credit risk assessment
• Customer churn prediction
• Fraud detection
6
IPH2445: Machine Learning using Python – III Chapter 1
y = mx + c
where
• m = slope
• x = input variable
• c = intercept
y = −2.3
or
y = 3.7
which cannot represent probabilities.
Key Point
Classification requires outputs between 0 and 1. Logistic Regression solves this
problem by transforming linear outputs into probabilities using the sigmoid func-
tion.
• 0 = Non-Diabetic
• 1 = Diabetic
Instead of directly predicting the class label, Logistic Regression predicts the proba-
bility that a patient belongs to the diabetic class.
Examples:
Probability Prediction
0.90 Diabetic
0.75 Diabetic
0.45 Non-Diabetic
0.10 Non-Diabetic
7
IPH2445: Machine Learning using Python – III Chapter 1
0≤P ≤1
where
• P = 0 indicates impossibility.
• P = 1 indicates certainty.
Examples:
Probability Interpretation
0.95 Very likely
0.75 Likely
0.50 Uncertain
0.25 Unlikely
0.05 Very unlikely
0.5
Decision rule:
P ≥ 0.5 ⇒ Class 1
8
IPH2445: Machine Learning using Python – III Chapter 1
• z = input value
z σ(z)
-4 0.018
-2 0.119
0 0.500
2 0.881
4 0.982
9
IPH2445: Machine Learning using Python – III Chapter 1
σ(z) = 0.5
which corresponds to
z=0
This boundary separates the two classes.
z=2
Then
1
σ(2) =
1 + e−2
1
=
1 + 0.1353
= 0.881
Thus,
P = 0.881
Since
1. Medical diagnosis
5. Sentiment analysis
6. Fraud detection
10
IPH2445: Machine Learning using Python – III Chapter 1
2.12 Summary
• Logistic Regression is a classification algorithm.
• Logistic Regression uses the sigmoid function to constrain outputs between 0 and
1.
• The sigmoid function produces an S-shaped curve suitable for binary classification.
3. Define probability.
Descriptive Questions
1. Explain the need for Logistic Regression.
11
IPH2445: Machine Learning using Python – III Chapter 1
Application-Oriented Questions
1. A hospital predicts a diabetes probability of 0.82 for a patient. Determine the
predicted class using a threshold of 0.5.
2. A bank uses Logistic Regression to assess loan risk. Explain how probability esti-
mates assist decision-making.
4. Explain how Logistic Regression can be used for email spam detection.
5. Design a simple binary classification problem that can be solved using Logistic
Regression.
3.2 Introduction
In the previous section, Logistic Regression was introduced as a classification algorithm
that predicts probabilities using the sigmoid function. However, a fundamental question
remains:
How does Logistic Regression transform a linear combination of input features into a
probability?
The answer lies in the concepts of odds, log-odds, and the logit function. These
concepts form the mathematical foundation of Logistic Regression and allow probabilities
to be modeled using linear equations.
12
IPH2445: Machine Learning using Python – III Chapter 1
0≤P ≤1
where:
• P = 0 indicates impossibility.
• P = 1 indicates certainty.
For example,
P = 0.80
means there is an 80% chance that the event occurs.
While probabilities are useful, Logistic Regression does not model probabilities di-
rectly. Instead, it models odds.
3.4 Odds
Definition
Odds represent the ratio of the probability that an event occurs to the probability
that it does not occur.
Mathematically,
P
Odds =
1−P
where:
• P = probability of success
• (1 − P ) = probability of failure
Example 1
Suppose
P = 0.75
Then
0.75 0.75
Odds = = =3
1 − 0.75 0.25
This means the event is three times more likely to occur than not occur.
13
IPH2445: Machine Learning using Python – III Chapter 1
Example 2
Suppose
P = 0.20
Then
0.20
Odds = = 0.25
0.80
The event is less likely to occur than not occur.
0→∞
Unlike probabilities, odds are not restricted to the interval [0, 1].
3.6 Log-Odds
The odds ratio is always positive and can become very large. This makes it inconvenient
for linear modeling.
To overcome this difficulty, Logistic Regression applies the natural logarithm to the
odds.
Definition
The logarithm of the odds is called the log-odds.
Mathematically,
P
Log-Odds = ln
1−P
The log-odds can take any value from
−∞ to +∞
which makes them suitable for linear equations.
14
IPH2445: Machine Learning using Python – III Chapter 1
P = 0.80
First compute the odds:
0.80
=4
0.20
Then
P = 0.20
then
0.20
= 0.25
0.80
and
ln(0.25) = −1.386
Notice:
(0, 1)
to the interval
(−∞, +∞)
This transformation allows a linear model to be constructed.
15
IPH2445: Machine Learning using Python – III Chapter 1
• β0 = intercept
• β1 = coefficient
• x = input feature
P → Log-Odds
while sigmoid transforms
Log-Odds → P
Thus,
1
P =
1 + e−z
where
z = β0 + β 1 x
The sigmoid function converts linear outputs into probabilities.
Definition
The decision boundary is the line, curve or surface that separates different classes.
P = 0.5
16
IPH2445: Machine Learning using Python – III Chapter 1
At this point,
Odds = 1
and
ln(1) = 0
Therefore,
β0 + β 1 x = 0
This equation defines the decision boundary.
z = −4 + 2x
The decision boundary occurs when
z=0
Thus,
−4 + 2x = 0
x=2
Therefore:
z = β0 + β1 x1 + β2 x2
The decision boundary is obtained by setting
z=0
giving
β 0 + β 1 x1 + β 2 x2 = 0
which represents a straight line in a two-dimensional feature space.
This line separates the two classes predicted by the model.
17
IPH2445: Machine Learning using Python – III Chapter 1
3.14 Applications
Odds, log-odds and decision boundaries are widely used in:
1. Medical diagnosis
4. Fraud detection
5. Marketing analytics
3.15 Summary
• Odds measure the likelihood of success relative to failure.
• The logit function transforms probabilities into values ranging from −∞ to +∞.
2. Define log-odds.
18
IPH2445: Machine Learning using Python – III Chapter 1
Descriptive Questions
1. Explain the concept of odds with suitable examples.
Application-Oriented Questions
1. A patient has a disease probability of 0.8. Calculate the odds and log-odds.
5. A bank predicts a loan default probability of 0.3. Compute the odds and interpret
the result.
19
IPH2445: Machine Learning using Python – III Chapter 1
4.2 Introduction
In the previous sections, we studied the mathematical foundations of Logistic Regression,
including probability, odds, log-odds, sigmoid functions and decision boundaries.
In practical machine learning applications, these calculations are performed automat-
ically using machine learning libraries. One of the most widely used libraries for machine
learning in Python is Scikit-Learn.
Scikit-Learn provides efficient implementations of many machine learning algorithms,
including Logistic Regression.
The typical workflow consists of:
This section demonstrates the implementation of Logistic Regression using the Iris
dataset.
• NumPy
• SciPy
• Matplotlib
• Classification
• Regression
• Clustering
• Dimensionality Reduction
• Model Evaluation
• Data Preprocessing
import sklearn
20
IPH2445: Machine Learning using Python – III Chapter 1
1. Iris Setosa
2. Iris Versicolor
3. Iris Virginica
1. Sepal Length
2. Sepal Width
3. Petal Length
4. Petal Width
iris = load_iris()
X = [Link]
y = [Link]
Here,
21
IPH2445: Machine Learning using Python – III Chapter 1
print([Link])
print([Link])
Output:
(150, 4)
(150,)
This indicates:
print(iris.target_names)
Output:
• Training Set
• Testing Set
Here:
22
IPH2445: Machine Learning using Python – III Chapter 1
model = LogisticRegression(max_iter=200)
[Link](X_train, y_train)
The fit() method trains the model using the training data.
Mathematically, the model learns the coefficients
β0 , β1 , β2 , β3 , β4
that best separate the flower classes.
y_pred = [Link](X_test)
[1 0 2 1 1]
where:
• 0 = Setosa
• 1 = Versicolor
• 2 = Virginica
Prediction:
23
IPH2445: Machine Learning using Python – III Chapter 1
sample = [[5.1,3.5,1.4,0.2]]
prediction = [Link](sample)
print(prediction)
Output:
[0]
model.predict_proba(sample)
Example output:
Interpretation:
• 1% probability of Versicolor
• 1% probability of Virginica
print(model.coef_)
24
IPH2445: Machine Learning using Python – III Chapter 1
accuracy = accuracy_score(y_test,y_pred)
print(accuracy)
Example output:
0.97
97%
iris = load_iris()
X = [Link]
y = [Link]
model = LogisticRegression(max_iter=200)
[Link](X_train,y_train)
y_pred = [Link](X_test)
print("Accuracy:",
accuracy_score(y_test,y_pred))
25
IPH2445: Machine Learning using Python – III Chapter 1
6. Calculate accuracy.
Expected Outcome
Students should be able to:
4.16 Summary
• Scikit-Learn provides an efficient implementation of Logistic Regression.
• Machine learning workflows involve data loading, training, testing and evaluation.
26
IPH2445: Machine Learning using Python – III Chapter 1
7. What is accuracy?
Descriptive Questions
1. Explain the workflow of implementing Logistic Regression using Scikit-Learn.
Application-Oriented Questions
1. Build a Logistic Regression model to classify flowers using the Iris dataset.
2. Predict the class of a flower with given measurements and interpret the probability
outputs.
5. Modify the program to classify a different dataset and compare the results.
27
IPH2445: Machine Learning using Python – III Chapter 1
5.2 Introduction
Developing a machine learning model is only the first step in solving a classification
problem. A model that performs well on the training data may not necessarily perform
well on new, unseen data.
Therefore, machine learning practitioners must evaluate how effectively a model gen-
eralizes beyond the data used during training.
Model evaluation helps answer important questions:
A reliable model should perform consistently on both training and testing datasets.
28
IPH2445: Machine Learning using Python – III Chapter 1
Key Point
The ultimate goal of machine learning is not to achieve perfect training accuracy
but to make accurate predictions on unseen data.
1. Training Set
2. Testing Set
Training Set
The training set is used to learn model parameters.
For Logistic Regression, the coefficients are estimated using the training data.
Testing Set
The testing set is not used during training.
It is used only after the model has been trained to evaluate performance on unseen
data.
In Scikit-Learn:
29
IPH2445: Machine Learning using Python – III Chapter 1
Here:
Definition
Accuracy is the proportion of correctly classified observations among all observa-
tions.
Mathematically,
Number of Correct Predictions
Accuracy =
Total Number of Predictions
or
TP + TN
Accuracy =
TP + TN + FP + FN
where
• TP = True Positives
• TN = True Negatives
• FP = False Positives
• FN = False Negatives
• Correct predictions = 92
• Incorrect predictions = 8
Then
92
Accuracy = = 0.92
100
Therefore,
Accuracy = 92%
The model correctly classifies 92 out of every 100 observations.
30
IPH2445: Machine Learning using Python – III Chapter 1
accuracy = accuracy_score(y_test,y_pred)
Example output:
Accuracy = 0.9667
This corresponds to
96.67%
classification accuracy.
1. Training Accuracy
2. Testing Accuracy
Training Accuracy
Performance on training data.
train_accuracy =
[Link](X_train,y_train)
Testing Accuracy
Performance on unseen data.
test_accuracy =
[Link](X_test,y_test)
31
IPH2445: Machine Learning using Python – III Chapter 1
5.10 Underfitting
Definition
Underfitting occurs when a model is too simple to capture the underlying patterns
in the data.
Characteristics:
• Low training accuracy
• Low testing accuracy
• Poor learning performance
Example:
Training Accuracy = 60%
Testing Accuracy = 58%
The model has not learned enough from the data.
5.11 Overfitting
Definition
Overfitting occurs when a model learns the training data too well, including noise
and random fluctuations.
Characteristics:
• Very high training accuracy
• Significantly lower testing accuracy
• Poor generalization
Example:
Training Accuracy = 99%
Testing Accuracy = 75%
The model memorizes training examples instead of learning general patterns.
Key Point
A model should learn patterns rather than memorize data.
32
IPH2445: Machine Learning using Python – III Chapter 1
Example:
4. Perform cross-validation.
iris = load_iris()
X = [Link]
y = [Link]
model = LogisticRegression(max_iter=200)
33
IPH2445: Machine Learning using Python – III Chapter 1
[Link](X_train,y_train)
train_acc =
[Link](X_train,y_train)
test_acc =
[Link](X_test,y_test)
Sample Output:
5.16 Summary
• Model evaluation measures the effectiveness of machine learning models.
34
IPH2445: Machine Learning using Python – III Chapter 1
7. Define underfitting.
8. Define overfitting.
Descriptive Questions
1. Explain the importance of model evaluation.
Application-Oriented Questions
1. A classifier correctly predicts 180 out of 200 observations. Calculate its accuracy.
2. A model achieves 99% training accuracy and 72% testing accuracy. Explain the
likely problem.
4. Compare two classifiers with testing accuracies of 85% and 92% and discuss which
should be preferred.
5. Explain how increasing training data can reduce overfitting in a classification prob-
lem.
35