This project is a self-contained C++ implementation of a minimal linear algebra library, and a linear regression engine. The goal is to demonstrate how to implement the simplest linear regression from scratch, including the matrix operations such as multiplication, transpose, and inverse (via Gauss-Jordan elimination).
The results are validated below by comparing against numpy's least-squares (lstsq) and singular-value-decomposition (svd) routines.
| Method | |||||
|---|---|---|---|---|---|
| numpy.linalg.lstsq | 3.78468983 | -3.00517361 | 1.99251052 | -1.01022950 | 0.06021616 |
| numpy.linalg.svd | 3.78468983 | -3.00517361 | 1.99251052 | -1.01022950 | 0.06021616 |
| LinReg (inverse) | 3.78468983 | -3.00517361 | 1.99251052 | -1.01022950 | 0.06021616 |
| True values | 4.00000000 | -3.00000000 | 2.00000000 | -1.00000000 | 0.00100000 |
This repo uses the closed-form solution to linear regression, namely the normal equation, for
and:
Derivation of the normal equation: Video.
The
C++11 or later required.
make
- The Y and X data are given in
data/data_y_beta.csv, where the first column is Y and the rest is X. - In
main.cpp, the above csv file is read, and after./linreg, the$\beta$ values are printed.
BaseMatrix: Abstract base class for deriving matrix-like classes.DenseMatrix: Inherits fromBaseMatrixand stores dense 2D data usingstd::vector.- Inheritance is used to allow for extensible designs like
SparseMatrixin the future. - Smart pointers are used (C++11 or later) to ensure memory safety.
- Single-matrix operations, such as transpose or inverse, are methods of the
DenseMatrixobjects. - Two-matrix operations, such as multiplications or linear regression, are implemented in the
MatrixOperationsclass. - The
linearRegression()method adds the bias term automatically for intercept values and returns the$\beta$ values.