Batch gradient descent linear regression implemented from first principles — no ML frameworks, full convergence diagnostics.
A complete linear regression implementation built from the math up: batch gradient descent, cost tracking, and convergence diagnostics, with a CLI and plots. No scikit-learn — the point is to show the mechanics, not import them.
Anyone can call .fit(). This exists to demonstrate understanding of what .fit()
is doing: the gradient, the update rule, why the learning rate matters, and how to
tell whether the thing actually converged.
🔵 Complete — a foundations / from-scratch reference piece.
This implements batch gradient descent for simple (univariate) linear regression:
- Initialize slope
m = 0and interceptb = 0 - Forward pass — compute predictions:
ŷ = mx + b - Cost — compute Mean Squared Error:
MSE = (1/n) Σ(y − ŷ)² - Gradients — compute partial derivatives
∂MSE/∂mand∂MSE/∂b - Update —
m ← m − α·(∂MSE/∂m)andb ← b − α·(∂MSE/∂b) - Repeat until
MSE < toleranceormax_iteris reached
where α is the learning rate.
Test_Dataset.csv is a synthetic 10-point dataset with two columns (x, y):
| x | y |
|---|---|
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
| 4 | 400 |
| 5 | 500 |
| 6 | 600 |
| 7 | 700 |
| 8 | 900 |
| 9 | 800 |
| 10 | 1000 |
The data closely follows y ≈ 100x with minor noise (two rows are swapped), producing an analytical least-squares solution of approximately slope = 98.79, intercept = 6.67.
Requirements: Python 3.8+
# 1. (Recommended) create and activate a virtual environment
python -m venv venv
source venv/bin/activate # macOS / Linux
venv\Scripts\activate # Windows
# 2. Install dependencies
pip install -r requirements.txtpython LinearReg.py --file Test_Dataset.csvWith explicit hyperparameters:
python LinearReg.py --file Test_Dataset.csv --lr 0.01 --tol 1e-3 --max-iter 10000python LinearReg.py --xvals 1,2,3,4,5 --yvals 2,4,6,8,10 --lr 0.01 --tol 1e-3
--fileand--xvalsare mutually exclusive — you must use one or the other.
| Flag | Short | Default | Description |
|---|---|---|---|
--file |
-f |
— | Path to a CSV file with two columns: x,y (no header) |
--xvals |
-x |
— | Comma-separated x values (mutually exclusive with --file) |
--yvals |
-y |
— | Comma-separated y values (required when using --xvals) |
--lr |
-l |
0.01 |
Learning rate α |
--tol |
-t |
1e-3 |
MSE convergence tolerance — stops early when MSE drops below this |
--max-iter |
— | 10000 |
Maximum number of gradient descent iterations |
Terminal:
Converged at iteration 847, MSE=0.000931
Result: slope = 98.7879, intercept = 6.6667
Chart 1 — Regression Fit:
A scatter plot of the input data overlaid with the fitted line y = mx + b. The equation is printed in the legend.
Chart 2 — Cost vs. Iteration: A line plot of MSE at each gradient descent step. A healthy run shows MSE decreasing monotonically toward the convergence threshold.
| Parameter | Effect |
|---|---|
Learning rate (--lr) |
Controls the update step size. Too large → m and b oscillate and the cost diverges. Too small → very slow convergence. 0.01 works well for this dataset. |
Tolerance (--tol) |
The MSE threshold for early stopping. A looser tolerance (e.g. 1e-1) converges faster but produces a less precise fit. |
Max iterations (--max-iter) |
Safety cap. If the algorithm hasn't converged by this iteration count, it stops and prints the final MSE. |
Python · NumPy · Matplotlib