CSE-41XX
CS-4125 ML

Lecture 06: Logistic Regression

An in-depth explanation of logistic regression for binary and multiclass classification, including hypothesis representation, decision boundaries, cost function formulation, gradient descent, advanced optimization, and the one-vs-all strategy.

Classification

In classification problems, the target variable yy is a discrete value. We want to develop the logistic regression algorithm to determine which class a new input should fall into.

  • Classification problems:

    • Email \rightarrow spam / not spam?
    • Online transactions \rightarrow fraudulent (yes / no)?
    • Tumor \rightarrow malignant / benign?
  • Target Variable (yy):

    • y{0,1}y \in \{0, 1\}
    • 00: Negative class (absence of something, e.g., benign tumor, not spam)
    • 11: Positive class (presence of something, e.g., malignant tumor, spam)

We start with binary class problems, where yy can take on only two values (0 or 1). Later, we will look at multiclass classification problems, which extend binary classification.

Why Not Use Linear Regression for Classification?

Consider a tumor size vs. malignancy (00 or 11) dataset. We could try fitting a linear regression model hθ(x)=θTxh_\theta(x) = \theta^T x and thresholding its output:

  • Predict y=1y = 1 if hθ(x)0.5h_\theta(x) \ge 0.5
  • Predict y=0y = 0 if hθ(x)<0.5h_\theta(x) < 0.5

Linear regression thresholding attempt on classification data

In some simple cases, linear regression with thresholding seems to do a reasonable job of stratifying data points into two classes. However, it suffers from major issues:

  1. Sensitivity to Outliers: Adding a single positive training example (y=1y = 1) with a very large tumor size shifts the decision line, causing the threshold to misclassify existing positive examples as negative (y=0y = 0).
  2. Unbounded Hypothesis: We know y{0,1}y \in \{0, 1\}, but linear regression hypothesis hθ(x)h_\theta(x) can output values much larger than 11 or less than 00.

Logistic regression solves this by ensuring hypothesis values always lie strictly between 00 and 11. Despite the name "regression", logistic regression is a classification algorithm.


Hypothesis Representation

To output values bounded between 00 and 11, we modify our hypothesis function. In linear regression, we had:

hθ(x)=θTxh_\theta(x) = \theta^T x

For logistic regression, we wrap θTx\theta^T x inside a function g(z)g(z):

hθ(x)=g(θTx)h_\theta(x) = g(\theta^T x)

Where g(z)g(z) is defined as:

g(z)=11+ezg(z) = \frac{1}{1 + e^{-z}}

This function g(z)g(z) is called the sigmoid function or the logistic function.

Combining these equations gives the logistic regression hypothesis representation:

Logistic regression hypothesis formulation combining sigmoid and linear combination

hθ(x)=11+eθTxh_\theta(x) = \frac{1}{1 + e^{-\theta^T x}}

The Sigmoid Function Plot

The sigmoid function crosses 0.50.5 at the origin (z=0z = 0) and asymptotes at 00 (as zz \to -\infty) and 11 (as z+z \to +\infty).

Sigmoid function graph showing output bounded between 0 and 1

Given this hypothesis representation, our goal is to fit the parameters θ\theta to our training data.

Interpreting Hypothesis Output

When our hypothesis hθ(x)h_\theta(x) outputs a number, we interpret that value as the estimated probability that y=1y = 1 for a given input xx.

Example

Suppose feature vector xx contains:

  • x0=1x_0 = 1 (bias feature, as always)
  • x1=tumorSizex_1 = \text{tumorSize}

If hθ(x)=0.7h_\theta(x) = 0.7, it tells the patient that they have a 70%70\% probability of the tumor being malignant (y=1y = 1).

Formal Probability Notation

hθ(x)=P(y=1x;θ)h_\theta(x) = P(y = 1 \mid x; \theta)

This represents: "The probability that y=1y = 1, given xx, parameterized by θ\theta."

Since this is a binary classification task where yy must be either 00 or 11, the probabilities for the two outcomes must sum to 1:

P(y=1x;θ)+P(y=0x;θ)=1P(y = 1 \mid x; \theta) + P(y = 0 \mid x; \theta) = 1 P(y=0x;θ)=1P(y=1x;θ)P(y = 0 \mid x; \theta) = 1 - P(y = 1 \mid x; \theta)

Decision Boundary

The decision boundary gives a better understanding of what the hypothesis function computes and what its decision regions look like.

To make predictions:

  • Predict y=1y = 1 whenever hθ(x)0.5h_\theta(x) \ge 0.5
  • Predict y=0y = 0 whenever hθ(x)<0.5h_\theta(x) < 0.5

Looking at the sigmoid curve:

  • g(z)0.5g(z) \ge 0.5 whenever z0z \ge 0

Sigmoid function threshold at z = 0 resulting in g(z) = 0.5

Since z=θTxz = \theta^T x:

  • hθ(x)=g(θTx)0.5h_\theta(x) = g(\theta^T x) \ge 0.5 whenever θTx0\theta^T x \ge 0

Therefore:

  • Hypothesis predicts y=1y = 1 when θTx0\theta^T x \ge 0
  • Hypothesis predicts y=0y = 0 when θTx<0\theta^T x < 0

Linear Decision Boundary Example

Consider a system with hypothesis hθ(x)=g(θ0+θ1x1+θ2x2)h_\theta(x) = g(\theta_0 + \theta_1 x_1 + \theta_2 x_2).

Linear decision boundary example setup

Suppose parameters are chosen as:

θ=[311]    θTx=3+x1+x2\theta = \begin{bmatrix} -3 \\ 1 \\ 1 \end{bmatrix} \implies \theta^T x = -3 + x_1 + x_2

The model predicts y=1y = 1 when:

3+x1+x20    x1+x23-3 + x_1 + x_2 \ge 0 \implies x_1 + x_2 \ge 3

The line x1+x2=3x_1 + x_2 = 3 forms the decision boundary.

Linear decision boundary graph separating binary classes

  • Magenta (++ / 11) region: x1+x2>3x_1 + x_2 > 3 where hθ(x)>0.5h_\theta(x) > 0.5
  • Blue (oo / 00) region: x1+x2<3x_1 + x_2 < 3 where hθ(x)<0.5h_\theta(x) < 0.5
  • Straight Line: x1+x2=3x_1 + x_2 = 3 where hθ(x)=0.5h_\theta(x) = 0.5 exactly.

Key Note: The decision boundary is a property of the hypothesis and its parameters θ\theta, not of the dataset itself. We fit θ\theta using dataset training examples, but once θ\theta is determined, the boundary is defined entirely by θTx=0\theta^T x = 0.


Non-Linear Decision Boundaries

To fit complex non-linear data distributions, we can add higher-order polynomial features to our input vector, just like in polynomial linear regression.

Suppose our hypothesis includes quadratic terms:

hθ(x)=g(θ0+θ1x1+θ2x2+θ3x12+θ4x22)h_\theta(x) = g(\theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_1^2 + \theta_4 x_2^2)

Non-linear dataset distribution with circular decision needs

Suppose parameter values are fit as:

θ=[10011]\theta = \begin{bmatrix} -1 \\ 0 \\ 0 \\ 1 \\ 1 \end{bmatrix}

The model predicts y=1y = 1 when:

1+x12+x220    x12+x221-1 + x_1^2 + x_2^2 \ge 0 \implies x_1^2 + x_2^2 \ge 1

Plotting x12+x22=1x_1^2 + x_2^2 = 1 yields a circular decision boundary centered at the origin with radius 1:

Circular non-linear decision boundary generated by polynomial features

  • Outside the circle (x12+x221x_1^2 + x_2^2 \ge 1): Predicts y=1y = 1
  • Inside the circle (x12+x22<1x_1^2 + x_2^2 < 1): Predicts y=0y = 0

By using even higher-order polynomial features (e.g., x13,x12x2,x1x22,x24x_1^3, x_1^2 x_2, x_1 x_2^2, x_2^4), logistic regression can build arbitrarily complex non-linear decision boundaries (ellipses, complex curves, etc.).


Cost Function for Logistic Regression

Given a training set of mm examples:

{(x(1),y(1)),(x(2),y(2)),,(x(m),y(m))}\{(x^{(1)}, y^{(1)}), (x^{(2)}, y^{(2)}), \dots, (x^{(m)}, y^{(m)})\}

Where each example x(i)Rn+1x^{(i)} \in \mathbb{R}^{n+1} (with x0=1x_0 = 1) and y(i){0,1}y^{(i)} \in \{0, 1\}.

Logistic regression training set definition and notation

How do we fit the parameters θ\theta?

Why Squared Error Fails for Logistic Regression

In linear regression, we used the mean squared error cost function:

Linear regression cost function formulation

J(θ)=1mi=1m12(hθ(x(i))y(i))2J(\theta) = \frac{1}{m} \sum_{i=1}^m \frac{1}{2} \left( h_\theta(x^{(i)}) - y^{(i)} \right)^2

If we define the individual example cost as:

Cost(hθ(x),y)=12(hθ(x)y)2\text{Cost}(h_\theta(x), y) = \frac{1}{2} (h_\theta(x) - y)^2

Sum of individual example costs representation

Then J(θ)J(\theta) can be rewritten as:

J(θ)=1mi=1mCost(hθ(x(i)),y(i))J(\theta) = \frac{1}{m} \sum_{i=1}^m \text{Cost}(h_\theta(x^{(i)}), y^{(i)})

If we plug the non-linear sigmoid hypothesis hθ(x)=11+eθTxh_\theta(x) = \frac{1}{1 + e^{-\theta^T x}} into this squared error formula, J(θ)J(\theta) becomes a non-convex function with many local minima.

Comparison of non-convex and convex cost functions

If J(θ)J(\theta) is non-convex, standard gradient descent is not guaranteed to converge to the global minimum because it can get trapped in local minima.

Convex Logistic Regression Cost Function

To guarantee global convergence with gradient descent, we need a convex cost function Cost(hθ(x),y)\text{Cost}(h_\theta(x), y):

Convex cost function formulation for logistic regression

Cost(hθ(x),y)={log(hθ(x))if y=1log(1hθ(x))if y=0\text{Cost}(h_\theta(x), y) = \begin{cases} -\log(h_\theta(x)) & \text{if } y = 1 \\ -\log(1 - h_\theta(x)) & \text{if } y = 0 \end{cases}

Intuition & Plots

  1. Case y=1y = 1: Cost=log(hθ(x))\text{Cost} = -\log(h_\theta(x))

Plot of -log(h(x)) cost curve when y = 1

  • If y=1y = 1 and hθ(x)=1h_\theta(x) = 1, Cost=0\text{Cost} = 0 (perfect prediction, zero penalty).
  • As hθ(x)0h_\theta(x) \to 0, Cost\text{Cost} \to \infty. This penalizes the model heavily if it predicts probability 00 when y=1y = 1.
  1. Case y=0y = 0: Cost=log(1hθ(x))\text{Cost} = -\log(1 - h_\theta(x))

Plot of -log(1 - h(x)) cost curve when y = 0

  • If y=0y = 0 and hθ(x)=0h_\theta(x) = 0, Cost=0\text{Cost} = 0 (perfect prediction, zero penalty).
  • As hθ(x)1h_\theta(x) \to 1, Cost\text{Cost} \to \infty. This penalizes the model heavily if it predicts probability 11 when y=0y = 0.

Using this cost function ensures that J(θ)J(\theta) is strictly convex and free of local minima.


Simplified Cost Function and Gradient Descent

Because y{0,1}y \in \{0, 1\} in binary classification, we can compress the two cases of Cost(hθ(x),y)\text{Cost}(h_\theta(x), y) into a single line formula:

Single-line compressed cost function formula for binary classification

Cost(hθ(x),y)=ylog(hθ(x))(1y)log(1hθ(x))\text{Cost}(h_\theta(x), y) = -y \log(h_\theta(x)) - (1 - y) \log(1 - h_\theta(x))

Verification

  • When y=1y = 1: Cost=(1)log(hθ(x))(0)log(1hθ(x))=log(hθ(x))\text{Cost} = -(1)\log(h_\theta(x)) - (0)\log(1 - h_\theta(x)) = -\log(h_\theta(x))
  • When y=0y = 0: Cost=(0)log(hθ(x))(1)log(1hθ(x))=log(1hθ(x))\text{Cost} = -(0)\log(h_\theta(x)) - (1)\log(1 - h_\theta(x)) = -\log(1 - h_\theta(x))

This compact formulation allows us to express the full cost function J(θ)J(\theta) as:

Full parameterized cost function J(theta) equation

J(θ)=1mi=1m[y(i)log(hθ(x(i)))+(1y(i))log(1hθ(x(i)))]J(\theta) = -\frac{1}{m} \sum_{i=1}^m \left[ y^{(i)} \log\left(h_\theta(x^{(i)})\right) + \left(1 - y^{(i)}\right) \log\left(1 - h_\theta(x^{(i)})\right) \right]

Statistical Origin: This cost function is derived from maximum likelihood estimation (MLE) under a Bernoulli likelihood assumption. It is convex and guarantees global optimization.

Gradient Descent Updates

To fit parameters θ\theta, we want to find θ\theta that minimizes J(θ)J(\theta):

minθJ(θ)\min_\theta J(\theta)

We use gradient descent to iteratively update each parameter θj\theta_j:

Gradient descent update rule for logistic regression parameters

Repeat until convergence: {θj:=θjαθjJ(θ)}\text{Repeat until convergence: } \left\{ \theta_j := \theta_j - \alpha \frac{\partial}{\partial \theta_j} J(\theta) \right\}

Calculating the partial derivative of J(θ)J(\theta) with respect to θj\theta_j:

θjJ(θ)=1mi=1m(hθ(x(i))y(i))xj(i)\frac{\partial}{\partial \theta_j} J(\theta) = \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right) x_j^{(i)}

Substituting this back gives the explicit parameter update rule:

Detailed parameter update formula with partial derivatives

Repeat until convergence: {θj:=θjα1mi=1m(hθ(x(i))y(i))xj(i)for j=0,,n}\text{Repeat until convergence: } \left\{ \theta_j := \theta_j - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)} \right) x_j^{(i)} \quad \text{for } j = 0, \dots, n \right\}

All parameters θ0,θ1,,θn\theta_0, \theta_1, \dots, \theta_n must be updated simultaneously.

Note: While this parameter update rule looks identical to linear regression, it is NOT identical because hθ(x)h_\theta(x) for logistic regression is g(θTx)=11+eθTxg(\theta^T x) = \frac{1}{1 + e^{-\theta^T x}}, whereas linear regression uses hθ(x)=θTxh_\theta(x) = \theta^T x.

Vectorized Implementation

In vector notation:

θ:=θαmXT(g(Xθ)y)\theta := \theta - \frac{\alpha}{m} X^T \left( g(X\theta) - y \right)

Feature scaling (mean normalization, scaling by range/standard deviation) applies to logistic regression gradient descent in the exact same manner as in linear regression to speed up convergence.


Advanced Optimization

For large-scale machine learning problems with many features, standard gradient descent can be slow. Advanced optimization algorithms exist to minimize J(θ)J(\theta) much faster.

Prerequisites for Optimization Algorithms

To use optimization routines, we need code that takes θ\theta as input and computes:

  1. J(θ)J(\theta) (the cost value)
  2. θjJ(θ)\frac{\partial}{\partial \theta_j} J(\theta) (the partial derivative vector for j=0,,nj = 0, \dots, n)

Input requirements for advanced optimization algorithms

Advanced Optimization Algorithms

  • Conjugate Gradient
  • BFGS (Broyden-Fletcher-Goldfarb-Shanno)
  • L-BFGS (Limited-memory BFGS)

Advantages

  • No manual learning rate (α\alpha): They use an internal line search algorithm to pick optimal step sizes for each iteration.
  • Faster convergence: Typically converge much faster than standard gradient descent.

Disadvantages

  • More complex; should be accessed via optimized numerical libraries rather than written from scratch.

Using Advanced Optimization Algorithms (Octave / MATLAB)

Consider a simple test optimization problem with two parameters θ1,θ2\theta_1, \theta_2:

J(θ)=(θ15)2+(θ25)2J(\theta) = (\theta_1 - 5)^2 + (\theta_2 - 5)^2 Jθ1=2(θ15),Jθ2=2(θ25)\frac{\partial J}{\partial \theta_1} = 2(\theta_1 - 5), \quad \frac{\partial J}{\partial \theta_2} = 2(\theta_2 - 5)

Cost function definition for Octave optimization example

1. Define the Cost Function

Octave function implementation returning cost value and gradient vector

function [jVal, gradient] = costFunction(theta)
  jVal = (theta(1)-5)^2 + (theta(2)-5)^2;
  gradient = zeros(2,1);
  gradient(1) = 2*(theta(1)-5);
  gradient(2) = 2*(theta(2)-5);
end

2. Execute fminunc

Octave options configuration and fminunc execution

options = optimset('GradObj', 'on', 'MaxIter', 100);
initialTheta = zeros(2,1);

[optTheta, functionVal, exitFlag] = fminunc(@costFunction, initialTheta, options);
  • optimset('GradObj', 'on', 'MaxIter', 100): Tells Octave that costFunction provides explicit gradient vectors and sets maximum iterations to 100.
  • fminunc: Stands for find minimum of unconstrained multivariable function.
  • @costFunction: Function handle pointing to the user function.

Multiclass Classification Problems

In multiclass classification, the outcome variable yy can take on more than two discrete values (y{1,2,3,,K}y \in \{1, 2, 3, \dots, K\}).

  • Examples:
    • Email tagging: Work (y=1y=1), Friends (y=2y=2), Family (y=3y=3), Hobby (y=4y=4)
    • Medical diagnosis: Not sick (y=1y=1), Cold (y=2y=2), Flu (y=3y=3)
    • Weather: Sunny (y=1y=1), Cloudy (y=2y=2), Rain (y=3y=3), Snow (y=4y=4)

Multiclass classification dataset with three distinct classes

One-vs-All (One-vs-Rest) Classification

The One-vs-All strategy transforms a KK-class classification problem into KK separate binary classification problems.

One-vs-all method splitting multiclass problem into binary classifiers

Training Procedure

For a dataset with KK classes:

  1. Class 1 vs All: Set class 1 as positive (y=1y = 1) and all other classes as negative (y=0y = 0). Train classifier hθ(1)(x)h_\theta^{(1)}(x).
  2. Class 2 vs All: Set class 2 as positive (y=1y = 1) and all other classes as negative (y=0y = 0). Train classifier hθ(2)(x)h_\theta^{(2)}(x).
  3. \dots
  4. Class K vs All: Set class KK as positive (y=1y = 1) and all other classes as negative (y=0y = 0). Train classifier hθ(K)(x)h_\theta^{(K)}(x).

Each classifier hθ(i)(x)h_\theta^{(i)}(x) evaluates:

hθ(i)(x)=P(y=ix;θ)for i=1,,Kh_\theta^{(i)}(x) = P(y = i \mid x; \theta) \quad \text{for } i = 1, \dots, K

Prediction Procedure

Given a new input xx, evaluate all KK trained classifiers and pick the class ii that yields the highest estimated probability:

Prediction=argmaxihθ(i)(x)\text{Prediction} = \arg\max_i h_\theta^{(i)}(x)

On this page