CSE-403 Machine Learning

Linear Regression

Concepts, Gradient Descent, Ordinary Least Squares, Regularization and Model Evaluation

Md. Atikuzzaman
Lecturer, Department of Computer Science & Engineering
atik@cse.green.edu.bd

From Data to Prediction

A teacher wants to predict a student’s final mark using weekly study hours.

We start with a few observed students, fit a line, then use that line to predict new students.

DataModelErrorLearningEvaluation

Study hours
→
Linear model
→
Final mark

Why Linear Regression First?

Simple

It introduces the full ML pipeline without too much mathematical overhead.

Interpretable

Each coefficient shows how the prediction changes when a feature changes.

Foundation

Loss functions, optimization, overfitting and regularization all become visible.

Supervised Learning Notation

\[ \mathcal{D}=\{(\mathbf{x}^{(i)}, y^{(i)})\}_{i=1}^{n} \] \[ \mathbf{x}^{(i)}=[x_1^{(i)},x_2^{(i)},\ldots,x_d^{(i)}]^T,\quad y^{(i)}\in\mathbb{R} \]

n = number of training examples

d = number of input features

x = input/features

y = target/output

ŷ = model prediction

Dataset Example

#Study hours xFinal mark ySplit
1142Training
2250Training
3355Training
4460Training
5570Training
6675Training
7782Test
8888Test

Learning problem

Learn a function that maps study hours to final marks.

Input: x = study hours
Target: y = final mark
Model: ŷ = wx + b

The last two examples are kept for testing the model after training.

The Linear Regression Model

Simple linear regression

\[ \hat{y}=wx+b \]

Multiple linear regression

\[ \hat{y}=\theta_0+\theta_1x_1+\cdots+\theta_dx_d \] \[ \hat{y}=\boldsymbol{\theta}^{T}\tilde{\mathbf{x}},\quad \tilde{\mathbf{x}}=[1,x_1,\ldots,x_d]^T \]

Meaning

w or θj controls the effect of a feature.

b or θ0 is the intercept/bias term.

The model is linear in its parameters, not necessarily only a straight line in raw features.

Loss Function: How Wrong Is the Line?

\[ e^{(i)} = y^{(i)} - \hat{y}^{(i)} \] \[ J(w,b)=\frac{1}{2n}\sum_{i=1}^{n}(\hat{y}^{(i)}-y^{(i)})^2 \]

The factor \(\frac{1}{2}\) makes derivatives cleaner.

Residual

A residual is the vertical distance between the actual data point and the model’s predicted line.

Training tries to make the residuals small on average.

Interactive Concept: Move the Line

Change parameters

ŷ = 6.00x + 35.00
MSE
Prediction for 6.5h

The best line balances all points, not just one point.

Ordinary Least Squares (OLS)

OLS chooses the parameters that minimize the sum of squared residuals.

\[ \min_{\boldsymbol{\theta}} \; ||\mathbf{X}\boldsymbol{\theta}-\mathbf{y}||_2^2 \] \[ \boldsymbol{\theta}^{*}=(\mathbf{X}^{T}\mathbf{X})^{-1}\mathbf{X}^{T}\mathbf{y} \]

Important condition

The closed-form solution requires \(\mathbf{X}^{T}\mathbf{X}\) to be invertible.

If features are highly correlated or columns are redundant, use pseudo-inverse or regularization.

OLS Matrix View

\[ \mathbf{X}=\begin{bmatrix} 1 & x_1^{(1)} & \cdots & x_d^{(1)}\\ 1 & x_1^{(2)} & \cdots & x_d^{(2)}\\ \vdots & \vdots & \ddots & \vdots\\ 1 & x_1^{(n)} & \cdots & x_d^{(n)} \end{bmatrix},\quad \boldsymbol{\theta}=\begin{bmatrix}\theta_0\\\theta_1\\\vdots\\\theta_d\end{bmatrix},\quad \mathbf{y}=\begin{bmatrix}y^{(1)}\\y^{(2)}\\\vdots\\y^{(n)}\end{bmatrix} \] \[ \hat{\mathbf{y}}=\mathbf{X}\boldsymbol{\theta} \]

In practice, libraries solve this using numerically stable linear algebra rather than manually computing the inverse.

Gradient Descent: Learn by Small Corrections

\[ \theta_j := \theta_j - \alpha \frac{\partial J(\boldsymbol{\theta})}{\partial \theta_j} \]

α is the learning rate.

The gradient points toward increasing loss, so we move in the opposite direction.

Intuition

Start with a poor line, measure error, update the line, and repeat.

Gradient descent is especially useful when datasets are large or models are more complex.

Gradient Descent Derivatives

For \(\hat{y}=wx+b\):

\[ \frac{\partial J}{\partial w}=\frac{1}{n}\sum_{i=1}^{n}(\hat{y}^{(i)}-y^{(i)})x^{(i)} \] \[ \frac{\partial J}{\partial b}=\frac{1}{n}\sum_{i=1}^{n}(\hat{y}^{(i)}-y^{(i)}) \]

Update rules:

\[ w := w-\alpha\frac{\partial J}{\partial w},\quad b := b-\alpha\frac{\partial J}{\partial b} \]

Repeat until the loss stops decreasing or a fixed number of epochs is reached.

Interactive Gradient Descent

Training simulation

epoch 0 | w = 0.00 | b = 0.00 | loss = ...

Try a large learning rate. If the loss jumps, the step size is too aggressive.

Interactive Loss Curve and Fitted Line

Current fitted line during optimization

How the loss changes across epochs

epoch 0 | w = 0.000 | b = 0.000 | loss = ...

A good learning rate makes the loss curve decrease smoothly. If the curve oscillates or grows, the step size is too large.

Batch, Stochastic and Mini-Batch Gradient Descent

Batch GD

Uses the full dataset for each update.

Stable, but slow for very large data.

Stochastic GD

Uses one example for each update.

Fast but noisy.

Mini-batch GD

Uses a small batch of examples.

Most common in modern ML training.

Feature Scaling Matters

\[ x'_j=\frac{x_j-\mu_j}{\sigma_j} \]

Standardization makes features comparable in scale.

Why important?

Gradient descent may move slowly when one feature is in taka, another in square feet, and another in number of rooms.

Scaling can make training faster and more stable.

Multiple Linear Regression

House price example

Features may include:

  • size in square feet
  • number of bedrooms
  • distance from city center
  • building age
\[ \hat{price}=\theta_0+\theta_1(size)+\theta_2(bedrooms)+\theta_3(distance)+\theta_4(age) \]

The model remains linear in the parameters \(\theta\).

Polynomial Features: Still Linear Regression

\[ \hat{y}=\theta_0+\theta_1x+\theta_2x^2 \]

This model can fit a curve, but it is still linear in \(\theta_0,\theta_1,\theta_2\).

Careful

Higher-degree polynomial features can fit training data very well but may generalize poorly.

This leads to overfitting.

Underfitting, Best Fit and Overfitting

Underfitting Too simple: misses the trend Best fit Captures the main pattern Overfitting Too wiggly: fits noise too

Underfitting

The model is too simple and performs poorly on both training and test data.

High bias.

Best fit

The model captures the dominant pattern while still generalizing to unseen data.

Good bias–variance tradeoff.

Overfitting

The model follows the noise in the training set and usually performs poorly on new data.

High variance.

Teaching example: a student who only memorizes repeated questions may score well on familiar questions but fail on a new scenario-based exam. That is like overfitting.

Regularization: Control Model Complexity

General idea:

\[ \text{Training loss} + \lambda \times \text{Penalty} \]

The penalty discourages overly large parameter values.

Purpose

Regularization helps reduce overfitting and improve performance on new data.

λ controls the strength of the penalty.

Ridge Regression: L2 Regularization

\[ J_{ridge}(\boldsymbol{\theta})=\frac{1}{n}||\mathbf{X}\boldsymbol{\theta}-\mathbf{y}||_2^2+\lambda||\boldsymbol{\theta}||_2^2 \] \[ \boldsymbol{\theta}^{*}=(\mathbf{X}^{T}\mathbf{X}+\lambda\mathbf{I})^{-1}\mathbf{X}^{T}\mathbf{y} \]

Effect

Ridge shrinks coefficients toward zero but usually does not make them exactly zero.

Useful when features are correlated.

Lasso and Elastic Net

Lasso

\[ J_{lasso}=\frac{1}{n}||\mathbf{X}\boldsymbol{\theta}-\mathbf{y}||_2^2+\lambda||\boldsymbol{\theta}||_1 \]

Elastic Net

\[ J=\text{MSE}+\lambda_1||\boldsymbol{\theta}||_1+\lambda_2||\boldsymbol{\theta}||_2^2 \]

Key difference

Lasso can set some coefficients exactly to zero, so it can perform feature selection.

Elastic Net combines L1 and L2 penalties.

Model Evaluation Metrics

\[ MAE=\frac{1}{n}\sum_{i=1}^{n}|y^{(i)}-\hat{y}^{(i)}| \] \[ MSE=\frac{1}{n}\sum_{i=1}^{n}(y^{(i)}-\hat{y}^{(i)})^2,\quad RMSE=\sqrt{MSE} \] \[ R^2=1-\frac{\sum_i(y^{(i)}-\hat{y}^{(i)})^2}{\sum_i(y^{(i)}-\bar{y})^2} \]

How to choose?

MAE is easy to interpret.

MSE/RMSE punish large errors more strongly.

R² shows explained variance, but can be misleading alone.

Train, Validation and Test

Training set

Used to learn parameters.

Validation set

Used to tune choices such as degree, λ and learning rate.

Test set

Used once at the end to estimate real performance.

Never tune the model repeatedly on the test set, otherwise the test result becomes optimistic.

Residual Analysis

Good signs

  • Residuals are centered around zero.
  • No clear curve or pattern remains.
  • Error size is roughly stable across predictions.

Warning signs

  • Curved residual pattern: model too simple.
  • Increasing spread: non-constant variance.
  • Outliers: data quality or special cases.

Colab: From Dataset to Model


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

X = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([42, 50, 55, 60, 70, 75])

model = LinearRegression()
model.fit(X, y)

X_test = np.array([[7], [8]])
y_test = np.array([82, 88])
y_pred = model.predict(X_test)

print("w:", model.coef_[0])
print("b:", model.intercept_)
print("MAE:", mean_absolute_error(y_test, y_pred))
print("RMSE:", mean_squared_error(y_test, y_pred) ** 0.5)
print("R2:", r2_score(y_test, y_pred))
  

Common Mistakes

Data leakage

Using test information during training or preprocessing.

No scaling

Gradient descent becomes slow or unstable.

Only R²

A high R² does not guarantee useful predictions.

Ignoring residuals

Errors may reveal patterns the model missed.

Class Activity

Task

Use the dataset table and fit a line manually by trying different values of \(w\) and \(b\).

Then compare your answer with OLS or gradient descent.

Discussion

Which line looks good visually?

Which line has the lowest MSE?

Can a line fit every point perfectly?

Linear Regression Workflow

Collect data
→
Split data
→
Train model
→
Evaluate
→
Improve

Improvement may mean better features, scaling, regularization, more data or a different model.

Takeaways

Linear regression predicts a continuous value using a weighted sum of features.

OLS gives a closed-form solution when the matrix conditions are suitable.

Gradient descent learns parameters through repeated small updates.

Regularization controls model complexity and helps reduce overfitting.

Model evaluation requires test data, appropriate error metrics and residual analysis.

Questions?

Next: Logistic Regression and Classification