Introduction
Logistic regression is a supervised machine learning algorithm used for classification problems. Unlike linear regression, which predicts continuous numerical values, logistic regression predicts the probability that an observation belongs to a particular class.
For example, it can predict whether an email is spam or not spam, whether a customer will leave a service, or whether a patient has a particular condition.
In this tutorial, we will understand the mathematics behind logistic regression and implement a binary classification model using Python and scikit-learn.
1. What is Logistic Regression?
Logistic regression is primarily used for binary classification, where the target variable has two possible outcomes:
- 0: Negative class
- 1: Positive class
The algorithm calculates a weighted combination of input features and passes it through the sigmoid function to obtain a probability between 0 and 1.
For a single input feature, the model is:
z = β₀ + β₁x
Here:
- x is the input feature.
- β₀ is the intercept.
- β₁ is the coefficient.
- z is the linear score.
For multiple features, the equation becomes:
z = β₀ + β₁x₁ + β₂x₂ + ... + βₙxₙ
2. The Sigmoid Function
The sigmoid function converts the linear score into a probability.
P(Y = 1 | X) = 1 / (1 + e⁻ᶻ)
Here:
- P(Y = 1 | X) is the probability of the positive class.
- e is Euler's number, approximately 2.718.
- z is the linear score.
The sigmoid function produces an S-shaped curve. Its output is always between 0 and 1.
For example, if a model predicts a probability of 0.82, it means the estimated probability of the positive class is 82%.
Using a classification threshold of 0.5:
- Probability ≥ 0.5 → Predict class 1
- Probability < 0.5 → Predict class 0
The threshold can be adjusted depending on the problem.
3. How Logistic Regression Learns
The model learns the coefficients that best separate the classes by estimating their probabilities.
Instead of using the ordinary least squares method commonly associated with linear regression, logistic regression generally uses maximum likelihood estimation.
A commonly used loss function is binary cross-entropy:
L = −(1/n) Σ [yᵢ log(pᵢ) + (1 − yᵢ) log(1 − pᵢ)]
Where:
- n is the number of observations.
- yᵢ is the actual class.
- pᵢ is the predicted probability of class 1.
The model adjusts its coefficients to reduce this loss.
4. Python Implementation
We will use the Iris dataset available in scikit-learn. It contains measurements of iris flowers, including sepal length, sepal width, petal length, and petal width.
The original dataset contains three flower species. For this example, we will create a binary classification problem:
- Class 1: Setosa
- Class 0: Not Setosa
Step 1: Import the libraries
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.metrics import ( accuracy_score, confusion_matrix, classification_report ) Step 2: Load and prepare the dataset
iris = load_iris() X = iris.data y = (iris.target == 0).astype(int) print("Dataset shape:", X.shape) print("First five labels:", y[:5]) The input contains 150 observations and four numerical features. We convert the original target into a binary target by assigning 1 to Setosa and 0 to the other species.
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 ) We use 80% of the data for training and 20% for testing. Stratification preserves the class proportions in both sets.
Step 4: Train the logistic regression model
model = make_pipeline( StandardScaler(), LogisticRegression(max_iter=1000) ) model.fit(X_train, y_train) The pipeline standardizes the input features and trains the logistic regression model. The scaler learns its parameters only from the training data, helping prevent data leakage.
Step 5: Make predictions
y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] print("Predicted classes:", y_pred) print("Probabilities:", y_prob.round(3)) The predict() method returns the predicted class, while predict_proba() returns the estimated class probabilities.
Step 6: Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred)) print("Confusion Matrix:") print(confusion_matrix(y_test, y_pred)) print("Classification Report:") print(classification_report(y_test, y_pred)) Accuracy measures the proportion of correct predictions.
Accuracy = Correct predictions / Total predictions
The confusion matrix shows true positives, true negatives, false positives, and false negatives. Precision, recall, and F1-score provide additional information about classification performance.
5. Visualizing the Sigmoid Function
The following code plots the sigmoid function to show how a linear score is converted into a probability.
import numpy as np import matplotlib.pyplot as plt z = np.linspace(-8, 8, 200) p = 1 / (1 + np.exp(-z)) plt.plot(z, p) plt.axhline(0.5, linestyle="--") plt.xlabel("Linear score (z)") plt.ylabel("Probability") plt.title("Sigmoid Function") plt.grid(True) plt.show() The curve approaches 0 for very negative scores and 1 for very positive scores. At z = 0, the probability is exactly 0.5.
6. Advantages and Limitations
Advantages:
- Simple to implement and interpret.
- Produces probability estimates.
- Computationally efficient.
- Works well for linearly separable classes.
Limitations:
- Assumes a linear relationship between the features and the log-odds.
- May not capture complex nonlinear relationships without feature transformations.
- Can be affected by highly correlated features and outliers.
Conclusion
Logistic regression is an important classification algorithm in machine learning. It uses the sigmoid function to convert a linear score into a probability and then assigns a class based on a threshold.
In this tutorial, we implemented a binary logistic regression classifier using the Iris dataset, trained it with scikit-learn, and evaluated its predictions using accuracy and a confusion matrix.
Understanding logistic regression provides a foundation for more advanced classification algorithms.
References
- Scikit-learn documentation: Logistic Regression
- Scikit-learn documentation: Iris Plants Dataset
- Python documentation
AI disclosure: AI was used to assist with drafting and organizing this educational article. The author is responsible for reviewing the explanations and code before publication.