AWS Builder Center

Machine Learning from Scratch – Day 7: Understanding Logistic Regression

Understanding Logistic Regression

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 7
    Machine Learning from Scratch – Day 7: Understanding Logistic Regression This article

Introduction

Welcome to Day 7 of our Machine Learning from Scratch series!
In Day 6, we explored Linear Regression, our first Machine Learning algorithm, and learned how computers predict numerical values such as salaries, house prices, and sales.
But what if we don't want to predict a number?
Imagine these questions:
  • Is this email Spam or Not Spam?
  • Will a customer purchase a product or not?
  • Is a tumor Benign or Malignant?
  • Will a student Pass or Fail?
These problems require predicting categories rather than continuous numerical values.
This is where Logistic Regression comes into the picture.

1. What is Logistic Regression?

Logistic Regression is a Supervised Machine Learning algorithm primarily used for classification problems.
Unlike Linear Regression, which predicts continuous numerical values, Logistic Regression estimates the probability that an input belongs to a particular class.
For example, an email detection system might predict:
  • Spam probability: 0.90
  • Not Spam probability: 0.10
Based on a chosen decision threshold, the model classifies the email as Spam.
Real-world applications:
  • Email spam detection.
  • Fraud detection.
  • Customer churn prediction.
  • Disease classification.
  • Student pass/fail prediction.

2. How Does Logistic Regression Work?

Logistic Regression uses a mathematical function called the Sigmoid Function to convert model outputs into probabilities between 0 and 1.
The sigmoid function is represented as:
\[ \sigma(z)=\frac{1}{1+e^{-z}} \]
Where:
  • \(z\) = Linear combination of input features and model coefficients.
  • \(e\) = Mathematical constant approximately equal to 2.718.
  • \(\sigma(z)\) = Predicted probability.
The output always falls between 0 and 1.
For example:
Probability
Interpretation
0.90
90% probability
0.75
75% probability
0.50
50% probability
0.20
20% probability
0.05
5% probability
This makes it useful for classification tasks.

3. Understanding the Decision Threshold

A probability alone doesn't determine the final class. We need a decision threshold.
A commonly used threshold is 0.5.
For example:
  • Probability greater than or equal to 0.5 → Class 1.
  • Probability less than 0.5 → Class 0.
Example: Spam Detection
Suppose an email classification model produces a spam probability of 0.85.
Since 0.85 is greater than 0.5, the email is classified as Spam.
However, the threshold is not fixed. Depending on the application, we can adjust it.
For example, medical screening systems may use a lower threshold to reduce the chance of missing positive cases.

4. Types of Logistic Regression

Logistic Regression can be used for different classification scenarios.
A. Binary Logistic Regression
Used when there are exactly two possible classes.
Examples:
  • Pass or Fail.
  • Spam or Not Spam.
  • Fraud or Genuine.
B. Multinomial Logistic Regression
Used when the target variable contains three or more unordered categories.
Examples:
  • Classifying fruits as Apple, Banana, or Orange.
  • Predicting product categories.
  • Classifying different types of flowers.
C. Ordinal Logistic Regression
Used when the target categories have a meaningful order.
Examples:
  • Customer satisfaction: Low, Medium, High.
  • Product ratings: Poor, Average, Excellent.

5. Logistic Regression vs Linear Regression

This is an important comparison for Machine Learning beginners.
Feature
Linear Regression
Logistic Regression
Main purpose
Regression
Classification
Output
Continuous value
Probability
Function
Linear equation
Sigmoid / Softmax
Prediction
Numerical
Class label
Example
House price
Spam detection
Remember: Despite its name, Logistic Regression is primarily a classification algorithm.

6. Practical Implementation Using Python

Let's build a simple Logistic Regression model using Scikit-learn.
We'll use the Iris dataset to classify flowers into two categories.
Step 1: Import the libraries
from sklearn.datasets import load_irisfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score
Step 2: Load the dataset
iris = load_iris()X = iris.datay = iris.target# Select two flower classesmask = y != 2X = X[mask]y = y[mask]
Step 3: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)
Step 4: Train the model
model = LogisticRegression()model.fit(X_train, y_train)
Step 5: Make predictions
predictions = model.predict(X_test)print("Predictions:", predictions)
Step 6: Evaluate the model
accuracy = accuracy_score(y_test, predictions)print("Accuracy:", accuracy)
What did we accomplish?
  • Loaded a real-world dataset.
  • Selected two flower categories.
  • Divided the dataset into training and testing sets.
  • Trained a Logistic Regression model.
  • Predicted flower categories.
  • Evaluated the model using accuracy.
We have successfully implemented our first classification model!

7. How Do We Evaluate Classification Models?

Accuracy alone is not always enough to evaluate a classification model.
Some important evaluation metrics include:
Metric
Meaning
Accuracy
Overall percentage of correct predictions
Precision
How many predicted positive cases are actually positive
Recall
How many actual positive cases were correctly identified
F1-Score
Harmonic mean of precision and recall
Confusion Matrix
Shows correct and incorrect classifications
For example, in fraud detection, missing an actual fraudulent transaction can be costly. Therefore, recall may be particularly important.

Conclusion

Today, we explored Logistic Regression, an important classification algorithm in Machine Learning.
Let's revise what we learned:
  • Logistic Regression is a Supervised Learning algorithm.
  • It is primarily used for classification.
  • The sigmoid function converts model outputs into probabilities.
  • A decision threshold helps determine the predicted class.
  • It supports binary and multiclass classification approaches.
  • Scikit-learn makes implementation straightforward.
The biggest takeaway is understanding the difference between predicting a numerical value and predicting a category.

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 7
    Machine Learning from Scratch – Day 7: Understanding Logistic Regression This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article