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.
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:
wis the learned weight (slope)bis the learned bias (intercept)
linear_regression/
├── linear_regression.cpp # Main implementation file
├── README.md # Project documentation- A C++ compiler (G++, Clang, MSVC, etc.)
- Basic C++ knowledge
g++ -std=c++11 -o linear_regression main.cpp
./linear_regressiondouble 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.
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:
Where:
m= number of samplesyᵢ= actual targetŷᵢ= predicted value from the model
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:
Where:
alphais the learning rate- Derivatives are computed as:
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.
Iteration 0 | Cost: 36.53
Iteration 100 | Cost: 0.0342
Iteration 200 | Cost: 0.0141
...
Final model: y = 1.4921x + 1.0132- Linear regression
- Gradient descent
- Mean squared error (MSE)
- Optimization
- C++ vectors and functions
- 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)
Feel free to fork and submit pull requests if you want to:
- Improve performance
- Add features
- Write tests
- Add documentation
This project is licensed under the MIT License.
Inspired by classic machine learning textbooks and tutorials such as:
- Andrew Ng’s ML Course
- “Hands-On ML with Scikit-Learn & TensorFlow”