Linear & logistic regression

PDS Spring 2026 - ITU

Today’s topics

  • Introduction
  • Linear regression
    • Gradient descent
    • Least squares
  • Logistic regression
    • Sigmoid function
    • Maximum likelihood estimation

Intended Learning Outcomes (ILOs)

You should be able to:

  • Explain how linear regression works and apply it to new problems.
  • Describe the idea behind gradient descent.
  • Explain how logistic regression works and apply it to new problems.
  • Describe the idea behind maximum likelihood estimation.

About me

  • 2019-2022 - B.Sc. in Business Informatics
    DHBW, Germany

  • 2022-2023 - Software Developer
    ECOVIS RTS, Germany

  • 2022-2024 - Full-Stack Engineer
    Outreach360, Remote

  • 2023-2025 - M.Sc. in Data Science
    ITU, Denmark

  • 2025-2026 - Research Assistant
    PURRlab, ITU, Denmark

  • 2026-Now - PhD Student
    PURRlab, ITU, Denmark

About you

Scan to join

Admin/Logistics

  • Slides created with Quarto & Revealjs
  • Slides available as website and PDF
    • PDF does not include animations or interactive plots

Linear vs logistic regression

Linear regression

Features: weight, size, freshness, season

Task: Predict the price of a fish based on its features.

Logistic regression

Features: job satisfaction, salary, commute time

Task: Predict if a person should stay in their job or not.

Linear regression

Linear regression

Problem

How expensive is a fish that weighs 4.5 kg?


Our goal

We seek a simple formula that captures the relationship between weight and price.


Observations from the data

  • Heavier fish tend to cost more.
  • A straight line seems a good fit.

Linear regression

Simple Linear Regression Model (1 feature)

Hypothesis (prediction) function

\[ h_{\theta}(x) = \theta_0 + \theta_1 x \]

  • \(\theta_0\) = bias
  • \(\theta_1\) = weight

School / Math Notation

\[ y = mx + b \]

  • \(b\) = intercept
  • \(m\) = slope


What if we have multiple features?

Multiple Linear Regression Model (m features)

\[ h_{\theta}(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 + \theta_2 x^{(i)}_2 + \cdots + \theta_m x^{(i)}_m \]

  • \(\theta_0\) = bias
  • \(\theta_k\) = weight for feature \(k\)
  • \(x^{(i)}_k\) = value of feature \(k\) for the \(i\)-th sample
  • \(n\) = total number of data points
  • \(m\) = number of features. A feature can be anything: weight, length, etc.
  • Geometric view: this represents an m-dimensional hyperplane

Linear regression - Evaluation

How well does a line fit the data?

The error (residual) for each point is the difference between the predicted value and the actual value (predicted price - actual price):

Error (Residual)

\[ e^{(i)} = h_\theta(x^{(i)}) - y^{(i)} \]

  • \(e^{(i)}\) = error (residual) of the \(i\)-th sample
  • \(h_\theta(x^{(i)})\) = predicted value of the \(i\)-th sample
  • \(y^{(i)}\) = true value of the \(i\)-th sample
  • \(n\) = total number of samples


Common evaluation metrics

Mean Squared Error (MSE)

\[\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} e^{(i)2}\]

Mean Absolute Error (MAE)

\[\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |e^{(i)}|\]

Questions

  • Why are we taking the mean? Why not just sum of errors?
  • When might MAE be a better choice than MSE, and vice versa?

Linear Regression - Interactive

How well can you fit a line to the data?



Check out MLU-EXPLAIN for more:

Interactive Linear Regression Explanation






Gradient Descent

Problem

We can evaluate how good a line fits the data but how do we find the best parameters \(\theta\)?


Analogy

Imagine you’re standing on a hill in thick fog. You can’t see the valley below, but you can feel the slope under your feet. Take a small step in the direction of steepest descent, feel the new slope, and repeat.

Terminology

  • Cost & Loss Functions \(J(\theta)\):
    • Measures how well the model fits the data for given parameters \(\theta\).
    • Loss refers to the error for a single example, while cost is for the whole dataset. In practice, these terms are often used interchangeably.
    • Goal: Minimize \(J(\theta)\).
  • Gradient (Slope) \(\nabla J(\theta)\)
    • Vector of partial derivatives. Points in the direction of steepest ascent.
  • Learning Rate \(\alpha\)
    • Controls the step size (how much to move in the direction of the gradient).
  • Local/Global Minimum
    • A local minimum is the lowest point in its immediate neighborhood.
    • A global minimum is the lowest point (value) of the cost function across the entire parameter space.

Gradient Descent

How does gradient descent work, in general?

Gradient Descent Algorithm

  1. Start with random parameters \(\theta = [\theta_0, \theta_1, \dots, \theta_m]\)

  2. Define a cost function \(J(\theta)\)

  3. Compute the gradient (the direction of steepest ascent)
    \[ \nabla J(\theta) = \left[ \frac{\partial J}{\partial \theta_0}, \frac{\partial J}{\partial \theta_1}, \dots, \frac{\partial J}{\partial \theta_m} \right] \]

  4. Update parameters in the direction of steepest descent \[ \theta_m := \theta_m - \alpha \frac{\partial J}{\partial \theta_m} \]

  5. Repeat steps 3 and 4 until convergence (gradient close to zero)


What cost function do we use for linear regression?

Least squares method

Choose the parameters \(\theta\) that minimize the sum of squared errors:

\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]

Questions:

  • Can we also use MSE as the cost function?

Gradient Descent

How does the learning rate affect convergence?


Questions

  • What happens if the learning rate is too small? Too large?
  • How do we choose a good learning rate in practice?

Gradient Descent

Example: Gradient Descent Algorithm (1 iteration)

Data (weight, price):

\[ (0.5, 8), (1.0, 10), (1.5, 22), (2.0, 24), (2.5, 28), \] \[ (3.0, 30), (3.5, 38), (4.0, 25), (5.0, 45), (6.0, 57) \]

  1. Start with random parameters: \(\theta_0 = 20, \theta_1 = 0\)

Predictions: \(h_\theta(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 = 20 + 0 \, x^{(i)}_1\)

  1. Define the cost function (Mean Squared Error): \[ J(\theta_0, \theta_1) = \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]

  2. Compute the gradients (using the chain rule)

\[ \frac{\partial J}{\partial \theta_0} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot \frac{\partial h_\theta(x^{(i)})}{\partial \theta_0} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot 1 = -17,4 \]

\[ \frac{\partial J}{\partial \theta_1} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot \frac{\partial h_\theta(x^{(i)})}{\partial \theta_1} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)}_1 = -95 \]

  1. Update parameters (using learning rate \(\alpha = 0.01\)): \[ \theta_0 := \theta_0 - \alpha \frac{\partial J}{\partial \theta_0} = 20 - 0.01 \cdot (-17.4) = 20.174 \] \[ \theta_1 := \theta_1 - \alpha \frac{\partial J}{\partial \theta_1} = 0 - 0.01 \cdot (-95) = 0.95 \]

Gradient Descent

Do we need gradient descent for linear regression?

Using least squares allows us to compute the optimal parameters \(\theta\) directly without iteration.

Closed-form solution

1. Define the data and parameters (Matrix notation)

\[ X = \begin{pmatrix} 1 & x_1^{(1)} & x_2^{(1)} & \dots & x_m^{(1)} \\ 1 & x_1^{(2)} & x_2^{(2)} & \dots & x_m^{(2)} \\ \vdots & \vdots & \vdots & & \vdots \\ 1 & x_1^{(n)} & x_2^{(n)} & \dots & x_m^{(n)} \end{pmatrix}_{n \times (m+1)}, \quad \theta = \begin{pmatrix} \theta_0 \\ \theta_1 \\ \vdots \\ \theta_m \end{pmatrix}_{(m+1) \times 1}, \quad y = \begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{pmatrix}_{n \times 1} \]

The prediction for all points can be written in vector form:

\[ h_\theta(X) = X \theta \quad \text{remember for one point: } h_\theta(x^{(i)}) = \theta_0 + \theta_1 x_1^{(i)} + \cdots + \theta_m x_m^{(i)}\text{)} \]

2. Define the cost function in matrix form

\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 = \| X \theta - y \|_2^2 = (X\theta - y)^\top (X\theta - y) \]

3. Closed-form solution

Set the gradient of the cost function to zero and solve for \(\theta\):

\[ \theta = (X^\top X)^{-1} X^\top y \]

\[\text{$(X^\top X)$ must be invertible (features are linearly independent)}\]

Equivalent idea for a single parameter (e.g., \(\theta_1\)): \(\frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)}_1 = 0\)

This gives the exact solution for linear regression without iteration.

Linear regression - Implementation

How do we implement linear regression in practice?

# import libraries
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error

# define input data (e.g., weight and length of fish) and labels (price)
X = np.array([[1.0, 20], [1.5, 24], [2.0, 28], [2.5, 30]]) # input features (weight, length)
y = np.array([8, 10, 22, 24]) # target variable (price)

# fit linear regression model
reg_model = LinearRegression().fit(X, y)

# evaluation
y_pred = reg_model.predict(X)
mse = mean_squared_error(y, y_pred)
mae = mean_absolute_error(y, y_pred)

# coefficients (weights) and intercept (bias)
print("Coefficients: \n", reg_model.coef_)
print("Intercept: \n", reg_model.intercept_)

# new predictions
new_X = np.array([[3.0, 33]])
new_y_pred = reg_model.predict(new_X)
print(f"New predictions: {new_y_pred}")

Linear regression - Recap


Goal

Predict a continuous target variable (e.g., price) based on one or more input features (e.g., weight, length).

Model

\[ h_{\theta}(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 + \theta_2 x^{(i)}_2 + \cdots + \theta_m x^{(i)}_m \]


Evaluation

  • Mean Squared Error (MSE)
  • Mean Absolute Error (MAE)
  • …

Cost function

Least squares method: minimize the sum of squared errors between predictions and true values.

\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]


Optimization

  • Closed-form solution (no iteration needed) \(\rightarrow\) default option for linear regression
  • Gradient descent (iterative optimization) \(\rightarrow\) widely used in machine learning

Quiz - Linear regression

Scan to join

Logistic regression

Logistic regression

Problem

Predict whether a patient is sick based on their body temperature.


Our goal

We are no longer trying to predict a continuous number (like price), but a binary category: sick (1) or healthy (0).


Observations from the data

  • Healthy patients have temperatures around 36-37.5°C, while sick patients are mostly above 37.5°C.
  • A straight line doesn’t work here. We need a function that outputs values between 0 and 1.

Logistic regression

What function can we use to model this data?

Sigmoid function (logistic function)

\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]

  • Maps any real number to a continues value between 0 and 1
  • Produces an S-shaped curve
  • Predictions are converted into classes using a threshold, typically 0.5: \[ label^{(i)} = \begin{cases} 1 & \text{if } h_\theta(x^{(i)}) \ge 0.5 \\ 0 & \text{otherwise} \end{cases} \]
  • Sigmoid function adds non-linearity
  • At \(z = 0\), output is exactly 0.5


Logistic Regression Model (1 feature)

Hypothesis (prediction) function

In logistic regression, we apply the sigmoid function to a linear combination of inputs:

\[ h_{\theta}(x^{(i)}) = \sigma(z) = \frac{1}{1 + e^{-z}}, \quad z = \theta_0 + \theta_1 x^{(i)}_1 \]

  • \(\theta_0\) = intercept / bias
  • \(\theta_1\) = weight / slope
  • Output \(h_{\theta}(x^{(i)})\) is interpreted as the probability that \(y^{(i)}=1\)

What if we have multiple features?

Logistic Regression Model (m features)

\[ h_{\theta}(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}_1 + \cdots + \theta_m x^{(i)}_m) \]

  • \(\theta_0\) = bias
  • \(\theta_m\) = weight for feature \(m\)
  • Each \(x^{(i)}_m\) is the \(i\)-th sample and \(m\)-th feature

Logistic regression

How do we evaluate a logistic regression model?

See lecture about classification, evaluation.

Accuracy: 85%, AUC: 0.55

Accuracy: 59%, AUC: 0.72


Questions

  • Is it more important to correctly identify sick patients or healthy patients?
  • Why can the use of accuracy be misleading?

Logistic regression - Interactive

How well can you fit a logistic regression model to this data?


Check out MLU-EXPLAIN for more:

Interactive Logistic Regression Explanation

Maximum likelihood estimation

How do we find the best parameters?

Logistic regression in log-odds space

Let’s transform the axis of probabilities to log-odds. \[ \text{logit}(p) = \log\!\left(\frac{p}{1-p}\right) \]

The raw data is being pushed to ±∞ in log-odds space which is why we can’t use least squares to find the best parameters. Instead, we use maximum likelihood estimation (MLE) to find the parameters that make the data most probable.

MLE for logistic regression

1. Model log-odds as a linear function

\[ \text{logit}(p) = \theta_0 + \theta_1 x \]

2. Convert to probability using the sigmoid function

\[ h_\theta(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} \]

3. Calculate likelihood

\[ L(\theta) = \prod_{i=1}^{n} h_\theta(x^{(i)})^{y^{(i)}} (1 - h_\theta(x^{(i)}))^{1 - y^{(i)}} \]

Or equivalently, the log-likelihood (turns products into sums):

\[ \log L(\theta) = \sum_{i=1}^{n} \bigl[y^{(i)} \log h_\theta(x^{(i)}) + (1 - y^{(i)}) \log(1 - h_\theta(x^{(i)}))\bigr] \]

4. Adjust parameters with the goal of maximizing likelihood


Maximum likelihood estimation

Optimizing prameters using gradient descent

Example: Gradient Descent Algorithm (1 iteration)

Data (temperature, sick):
\[(36.0, 0), (36.3, 0), (36.5, 0), (36.8, 0), (37.0, 0), (37.2, 0), (37.5, 1), \]

\[ (37.8, 0), (38.0, 1), (38.3, 1), (38.7, 1), (39.0, 1), (39.5, 1), (40.0, 1) \]

1. Start with random parameters: \(\theta_0 = -115, \theta_1 = 3\)

\[ \text{Predictions: } h_\theta(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} \]

2. Cost Function (Log Loss / Cross-Entropy Loss)

We want to minimize the negative log-likelihood, which is equivalent to maximizing the log-likelihood:

\[ J(\theta) = - \frac{1}{n}\sum_{i=1}^{n} \left[ y_i \log(h_\theta(x^{(i)})) + (1 - y_i)\log(1 - h_\theta(x^{(i)})) \right] \]

3. Compute the gradients

\[ \frac{\partial J(\theta)}{\partial \theta_0} = \frac{1}{n}\sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) = \frac{1}{n}\sum_{i=1}^{n} (\frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} - y^{(i)}) = - 0.168 \]

\[ \frac{\partial J(\theta)}{\partial \theta_1} = \frac{1}{n}\sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)} = \frac{1}{n}\sum_{i=1}^{n} (\frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} - y^{(i)}) \cdot x^{(i)} = -6.388 \]

4. Update Parameters (Learning Rate \(\alpha = 0.01\))

\[ \theta_0 := \theta_0 - \alpha \cdot \frac{\partial J(\theta)}{\partial \theta_0} = -114.998 \quad \theta_1 := \theta_1 - \alpha \cdot \frac{\partial J(\theta)}{\partial \theta_1} = 3.06388 \]

Logistic regression - Parameters

Class weights

In cases of imbalanced datasets, we can assign different weights to classes to help the model focus more on the minority class.

from sklearn.linear_model import LogisticRegression

# you can use balanced class weights
model = LogisticRegression(class_weight='balanced')

# or custom weights for each class
model = LogisticRegression(class_weight={0: 1, 1: 5}) 


Feature scaling

Bring all features to the same scale as different scales can affect the convergence of the optimization algorithm used.

Note: Apply feature scaling after creating the train, validation, and test sets to avoid data leakage.

from sklearn.preprocessing import StandardScaler

# fit scaler on training data
scaler = StandardScaler()

# apply the same transformation to train, validation and test data
X_train_scaled = scaler.fit_transform(X_train)
X_val_scaled = scaler.transform(X_val)
X_test_scaled = scaler.transform(X_test)


Solver

Scikit-learn supports different optimization algorithms (solvers) for fitting a model.

  • Default solver for logistic regression is “lbfgs”.
  • Closest to gradient descent is the Stochastic Average Gradient “sag”” solver.

Logistic regression - Implementation

# import libraries
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score

# define input data 
X = np.array([[36.0], [36.3], [36.5], [36.8], [37.0], [37.2],
[37.5], [37.8], [38.0], [38.3], [38.7], [39.0], [39.5], [40.0]])
y = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1])

# fit logistic regression model
model = LogisticRegression(random_state=42, class_weight='balanced').fit(X, y)

# evaluation
y_pred = model.predict(X)
y_prob = model.predict_proba(X)[:, 1] # probability of class 1 (sick)

acc = accuracy_score(y, y_pred)
auc = roc_auc_score(y, y_prob)

# coefficients (weights) and intercept (bias)
print("Intercept: \n", model.intercept_)
print("Coefficients: \n", model.coef_)

# new predictions
new_X = np.array([[41.0]])
new_y_pred = model.predict(new_X)
print("New predictions: \n", new_y_pred)

Recap - Logistic regression

Goal

Predict the probability of a binary outcome
(e.g. sick = 1, healthy = 0).


Model

\[ h_{\theta}(x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x_1^{(i)} + \cdots + \theta_m x_m^{(i)})}} \]


Decision rule

Convert probability into a class using a threshold: \[ label^{(i)} = \begin{cases} 1 & \text{if } h_\theta(x^{(i)}) \ge 0.5 \\ 0 & \text{otherwise} \end{cases} \]


Cost function

Fit parameters by minimizing the negative log-likelihood: \[ J(\theta) = - \frac{1}{n}\sum_{i=1}^{n} \left[ y^{(i)} \log(h_\theta(x^{(i)})) + (1 - y^{(i)})\log(1 - h_\theta(x^{(i)})) \right] \]

Evaluation

  • Accuracy (can be misleading in imbalanced datasets)
  • Area Under the ROC Curve (AUC)

Example of logistic regression in practice

Reference: https://arxiv.org/abs/2504.11415

Quiz

Scan to join

Exercises

Part 1: Linear regression

  • Implement a linear regression model
  • Remove outliers
  • Evaluate the model


Part 2: Logistic regression

  • Implement a logistic regression model
  • Consider the use case. What evaluation metric would you use?
  • How would you handle class imbalance?