DEV Community

Logistic Regression: A Beginner's Guide with Python

Logistic Regression – A Beginner's Guide with Python

Category: Machine Learning | Data Science

1. Introduction

Machine Learning can be used not only to predict numerical values but also to classify information into categories.

For example, a bank may want to predict whether a transaction is fraudulent, or a doctor may study whether a test result indicates a possible condition.

Logistic Regression is a widely used supervised learning algorithm for classification.

2. What is Logistic Regression?

Logistic Regression is a supervised machine learning algorithm mainly used to predict the probability of a categorical outcome.

Although its name contains the word regression, it is commonly used for classification tasks such as:

  • Yes or No
  • 0 or 1
  • Spam or Not Spam
  • Pass or Fail

3. How Does Logistic Regression Work?

The algorithm calculates a weighted combination of input features and passes the result through the Sigmoid Function.

The sigmoid function converts the result into a probability between 0 and 1.

A threshold, often 0.5, can then be used to assign a class.

Mathematical Formula

p = 1 / (1 + e⁻ᶻ)

Where:

  • p: Predicted probability
  • e: Mathematical constant
  • z: Weighted sum of input features

Working Steps

  1. Provide input features.
  2. Calculate the weighted sum.
  3. Apply the sigmoid function.
  4. Calculate the probability.
  5. Assign the final class using a threshold.

Example: If the predicted probability of an email being spam is 0.90, the model may classify it as Spam using a threshold of 0.5.

4. Types of Logistic Regression

A. Binary Logistic Regression

Used when there are only two possible classes.

Example: Pass or Fail.

B. Multinomial Logistic Regression

Used when there are three or more unordered classes.

Example: Classifying fruits as Apple, Banana or Orange.

C. Ordinal Logistic Regression

Used when categories have a meaningful order.

Example: Low, Medium and High satisfaction.

5. Python Implementation

We can implement Logistic Regression using Python and the Scikit-learn library.

In this example, we use the Iris dataset and select two classes for binary classification.

Python Program

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = load_iris()

# Keep only the first two classes
X = iris.data[iris.target < 2]
y = iris.target[iris.target < 2]

# 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
)

# Create the model
model = LogisticRegression(max_iter=200)

# Train the model
model.fit(X_train, y_train)

# Make predictions
predictions = model.predict(X_test)

# Display accuracy
print("Accuracy:", round(
    accuracy_score(y_test, predictions) * 100, 2
), "%")

print("Predicted class for first test row:",
      model.predict([X_test[0]])[0])
Enter fullscreen mode Exit fullscreen mode

Sample Output

Accuracy: 100.0 %
Predicted class for first test row: 1
Enter fullscreen mode Exit fullscreen mode

Output Explanation

The model achieved 100% accuracy on this particular test split.

The predicted class for the first test row is 1, representing the second selected Iris class.

6. Real-Life Applications

Logistic Regression is used in various fields:

  1. Email spam detection.
  2. Customer churn prediction.
  3. Disease-risk classification.
  4. Loan default assessment.
  5. Fraud detection.

7. Advantages of Logistic Regression

  • Relatively simple to understand and train.
  • Provides probability-based predictions.
  • Computationally efficient for many datasets.
  • Useful as a baseline classification model.

8. Limitations of Logistic Regression

  • Creates a linear decision boundary unless features are transformed.
  • Performance can be affected by multicollinearity.
  • May struggle with complex patterns.
  • Performance can be affected by unbalanced classes.

9. Conclusion

Logistic Regression is a foundational classification algorithm in Machine Learning.

It is useful when we need a clear and efficient model that estimates class probabilities.

Learning Logistic Regression helps students understand classification, probability and the working of supervised machine learning algorithms.

10. References and Further Reading

  1. Scikit-learn Documentation
  2. TensorFlow Learning Resources
  3. GeeksforGeeks

Top comments (0)