Logistic Regression Basics

Introduction to Logistic Regression

Logistic regression is a type of classification algorithm used to predict the probability of a class or event existing. Unlike linear regression, which predicts a continuous number, logistic regression predicts a discrete outcome—a sort of yes or no, true or false, or in data terms, class 0 or class 1.

For example, imagine you have data on whether an email is spam or not. Logistic regression can help you predict whether a new email is spam based on its content.

You'll use logistic regression when you need to classify data into categories. Real-life examples include:

  • Predicting if a student will pass or fail
  • Determining whether an email is spam
  • Diagnosing whether a patient has a certain disease

How Logistic Regression Works:

Logistic regression works by fitting a logistic function (also known as the sigmoid function) to the data. The sigmoid function is defined as:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

where zz is the linear combination of input features:

z=w0+w1x1+w2x2+...+wnxnz = w_0 + w_1x_1 + w_2x_2 + ... + w_nx_n

Here, w0w_0 is the intercept (bias term), and w1,w2,...,wnw_1, w_2, ..., w_n are the weights (coefficients) associated with the input features x1,x2,...,xnx_1, x_2, ..., x_n.

The sigmoid function output is a probability value between 0 and 1. If this probability is greater than a certain threshold (commonly 0.5), the outcome is class 1 (e.g., the mail is spam). Otherwise, it is class 0 (e.g., the mail is not spam). The model adjusts the weights during training to minimize the difference between predicted and actual class labels.

Here is how the sigmoid function fits the classification data:

Example of Loading a Dataset

Before we can train a logistic regression model, we'll need some data. Scikit-Learn, a popular Python library for machine learning, provides many built-in datasets. For this lesson, we'll use the wine dataset, which helps predict the class of wine based on its chemical properties.

Python
from sklearn.datasets import load_wine

# Load real dataset
X, y = load_wine(return_X_y=True)
print(X.shape, y.shape)  # (178, 13) (178,)

Here, X represents the features (input data), and y represents the labels (output data) we want to predict. The wine dataset is well-known for this kind of task.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal