Skip to content

Latest commit

 

History

History
187 lines (121 loc) · 3.58 KB

README.md

File metadata and controls

187 lines (121 loc) · 3.58 KB

Linear Regression from Scratch in C++

A simple implementation of univariate linear regression using gradient descent in C++. This project demonstrates how a machine learning model can be built entirely from scratch without relying on external ML libraries.


Overview

This program fits a straight line to a set of training data points using gradient descent optimization to minimize mean squared error (MSE). The final output is a linear model of the form:

y = wx + b

Where:

  • w is the learned weight (slope)
  • b is the learned bias (intercept)

File Structure

linear_regression/
├── linear_regression.cpp        # Main implementation file
├── README.md       # Project documentation

Getting Started

Prerequisites

  • A C++ compiler (G++, Clang, MSVC, etc.)
  • Basic C++ knowledge

Compile and Run

g++ -std=c++11 -o linear_regression main.cpp
./linear_regression

Code Explanation

1. predict()

double predict(double x, double w, double b){
    return w * x + b;
}

Returns the predicted value ŷ given an input x using the current weight w and bias b.


2. compute_cost()

double compute_cost(const std::vector<double>& x, const std::vector<double>& y, double w, double b)

Calculates the Mean Squared Error between predicted and actual values:

$$ \text{MSE} = \frac{1}{m} \sum_{i=1}^m (\hat{y}_i - y_i)^2 $$

Where:

  • m = number of samples
  • yᵢ = actual target
  • ŷᵢ = predicted value from the model

3. gradientDescent()

void gradientDescent(const std::vector<double>& x, const std::vector<double>& y, double& w, double& b, double alpha, int iterations)

Iteratively updates the parameters w and b to minimize the cost function using gradient descent:

$$ w = w - \alpha \cdot \frac{\partial \text{Cost}}{\partial w} $$

$$ b = b - \alpha \cdot \frac{\partial \text{Cost}}{\partial b} $$

Where:

  • alpha is the learning rate
  • Derivatives are computed as:

$$ \frac{\partial \text{Cost}}{\partial w} = \frac{2}{m} \sum_{i=1}^m (\hat{y}_i - y_i)x_i $$

$$ \frac{\partial \text{Cost}}{\partial b} = \frac{2}{m} \sum_{i=1}^m (\hat{y}_i - y_i) $$


4. main()

Defines sample training data (x, y), initializes weights, runs gradient descent, and prints final model parameters:

std::vector<double> x = {1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0};
std::vector<double> y = {3.2, 4.1, 5.0, 5.8, 6.7, 7.5, 8.2, 9.1};

After training:

Final model: y = 1.49x + 1.01

This means our model has learned that y increases by ~1.49 for every unit increase in x, starting from a baseline of ~1.01.


Example Output

Iteration 0 | Cost: 36.53
Iteration 100 | Cost: 0.0342
Iteration 200 | Cost: 0.0141
...
Final model: y = 1.4921x + 1.0132

Concepts Covered

  • Linear regression
  • Gradient descent
  • Mean squared error (MSE)
  • Optimization
  • C++ vectors and functions

Future Improvements

  • Support for multivariate regression
  • Data normalization
  • Visualization (e.g., exporting results to CSV and plotting in Python/Excel)
  • Add convergence condition (e.g., stop if cost change < epsilon)

Contributing

Feel free to fork and submit pull requests if you want to:

  • Improve performance
  • Add features
  • Write tests
  • Add documentation

License

This project is licensed under the MIT License.


Acknowledgments

Inspired by classic machine learning textbooks and tutorials such as:

  • Andrew Ng’s ML Course
  • “Hands-On ML with Scikit-Learn & TensorFlow”