-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add Simple Linear Regression Algorithm #538
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
siriak
merged 2 commits into
TheAlgorithms:master
from
ngtduc693:feature/add-linear-regression
Oct 4, 2025
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
using Algorithms.MachineLearning; | ||
|
||
namespace Algorithms.Tests.MachineLearning; | ||
|
||
/// <summary> | ||
/// Unit tests for the LinearRegression class. | ||
/// </summary> | ||
public class LinearRegressionTests | ||
{ | ||
[Test] | ||
public void Fit_ThrowsException_WhenInputIsNull() | ||
{ | ||
var lr = new LinearRegression(); | ||
Assert.Throws<ArgumentException>(() => lr.Fit(null!, new List<double> { 1 })); | ||
Assert.Throws<ArgumentException>(() => lr.Fit(new List<double> { 1 }, null!)); | ||
} | ||
|
||
[Test] | ||
public void Fit_ThrowsException_WhenInputIsEmpty() | ||
{ | ||
var lr = new LinearRegression(); | ||
Assert.Throws<ArgumentException>(() => lr.Fit(new List<double>(), new List<double>())); | ||
} | ||
|
||
[Test] | ||
public void Fit_ThrowsException_WhenInputLengthsDiffer() | ||
{ | ||
var lr = new LinearRegression(); | ||
Assert.Throws<ArgumentException>(() => lr.Fit(new List<double> { 1 }, new List<double> { 2, 3 })); | ||
} | ||
|
||
[Test] | ||
public void Fit_ThrowsException_WhenXVarianceIsZero() | ||
{ | ||
var lr = new LinearRegression(); | ||
Assert.Throws<ArgumentException>(() => lr.Fit(new List<double> { 1, 1, 1 }, new List<double> { 2, 3, 4 })); | ||
} | ||
|
||
[Test] | ||
public void Predict_ThrowsException_IfNotFitted() | ||
{ | ||
var lr = new LinearRegression(); | ||
Assert.Throws<InvalidOperationException>(() => lr.Predict(1.0)); | ||
Assert.Throws<InvalidOperationException>(() => lr.Predict(new List<double> { 1.0 })); | ||
} | ||
|
||
[Test] | ||
public void FitAndPredict_WorksForSimpleData() | ||
{ | ||
// y = 2x + 1 | ||
var x = new List<double> { 1, 2, 3, 4 }; | ||
var y = new List<double> { 3, 5, 7, 9 }; | ||
var lr = new LinearRegression(); | ||
lr.Fit(x, y); | ||
Assert.That(lr.IsFitted, Is.True); | ||
Assert.That(lr.Intercept, Is.EqualTo(1.0).Within(1e-6)); | ||
Assert.That(lr.Slope, Is.EqualTo(2.0).Within(1e-6)); | ||
Assert.That(lr.Predict(5), Is.EqualTo(11.0).Within(1e-6)); | ||
} | ||
|
||
[Test] | ||
public void FitAndPredict_WorksForNegativeSlope() | ||
{ | ||
// y = -3x + 4 | ||
var x = new List<double> { 0, 1, 2 }; | ||
var y = new List<double> { 4, 1, -2 }; | ||
var lr = new LinearRegression(); | ||
lr.Fit(x, y); | ||
Assert.That(lr.Intercept, Is.EqualTo(4.0).Within(1e-6)); | ||
Assert.That(lr.Slope, Is.EqualTo(-3.0).Within(1e-6)); | ||
Assert.That(lr.Predict(3), Is.EqualTo(-5.0).Within(1e-6)); | ||
} | ||
|
||
[Test] | ||
public void Predict_List_WorksCorrectly() | ||
{ | ||
var x = new List<double> { 1, 2, 3 }; | ||
var y = new List<double> { 2, 4, 6 }; | ||
var lr = new LinearRegression(); | ||
lr.Fit(x, y); // y = 2x | ||
var predictions = lr.Predict(new List<double> { 4, 5 }); | ||
Assert.That(predictions[0], Is.EqualTo(8.0).Within(1e-6)); | ||
Assert.That(predictions[1], Is.EqualTo(10.0).Within(1e-6)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
|
||
namespace Algorithms.MachineLearning; | ||
|
||
/// <summary> | ||
/// Implements simple linear regression for one independent variable (univariate). | ||
/// Linear regression is a supervised learning algorithm used to model the relationship | ||
/// between a scalar dependent variable (Y) and an independent variable (X). | ||
/// The model fits a line: Y = a + bX, where 'a' is the intercept and 'b' is the slope. | ||
/// </summary> | ||
public class LinearRegression | ||
{ | ||
// Intercept (a) and slope (b) of the fitted line | ||
public double Intercept { get; private set; } | ||
|
||
public double Slope { get; private set; } | ||
|
||
public bool IsFitted { get; private set; } | ||
|
||
/// <summary> | ||
/// Fits the linear regression model to the provided data. | ||
/// </summary> | ||
/// <param name="x">List of independent variable values.</param> | ||
/// <param name="y">List of dependent variable values.</param> | ||
/// <exception cref="ArgumentException">Thrown if input lists are null, empty, or of different lengths.</exception> | ||
public void Fit(IList<double> x, IList<double> y) | ||
{ | ||
if (x == null || y == null) | ||
{ | ||
throw new ArgumentException("Input data cannot be null."); | ||
} | ||
|
||
if (x.Count == 0 || y.Count == 0) | ||
{ | ||
throw new ArgumentException("Input data cannot be empty."); | ||
} | ||
|
||
if (x.Count != y.Count) | ||
{ | ||
throw new ArgumentException("Input lists must have the same length."); | ||
} | ||
|
||
// Calculate means | ||
double xMean = x.Average(); | ||
double yMean = y.Average(); | ||
|
||
// Calculate slope (b) and intercept (a) | ||
double numerator = 0.0; | ||
double denominator = 0.0; | ||
for (int i = 0; i < x.Count; i++) | ||
{ | ||
numerator += (x[i] - xMean) * (y[i] - yMean); | ||
denominator += (x[i] - xMean) * (x[i] - xMean); | ||
} | ||
|
||
const double epsilon = 1e-12; | ||
if (Math.Abs(denominator) < epsilon) | ||
{ | ||
throw new ArgumentException("Variance of X must not be zero."); | ||
} | ||
|
||
Slope = numerator / denominator; | ||
Intercept = yMean - Slope * xMean; | ||
IsFitted = true; | ||
} | ||
|
||
/// <summary> | ||
/// Predicts the output value for a given input using the fitted model. | ||
/// </summary> | ||
/// <param name="x">Input value.</param> | ||
/// <returns>Predicted output value.</returns> | ||
/// <exception cref="InvalidOperationException">Thrown if the model is not fitted.</exception> | ||
public double Predict(double x) | ||
{ | ||
if (!IsFitted) | ||
{ | ||
throw new InvalidOperationException("Model must be fitted before prediction."); | ||
} | ||
|
||
return Intercept + Slope * x; | ||
} | ||
|
||
/// <summary> | ||
/// Predicts output values for a list of inputs using the fitted model. | ||
/// </summary> | ||
/// <param name="xValues">List of input values.</param> | ||
/// <returns>List of predicted output values.</returns> | ||
/// <exception cref="InvalidOperationException">Thrown if the model is not fitted.</exception> | ||
public IList<double> Predict(IList<double> xValues) | ||
{ | ||
if (!IsFitted) | ||
{ | ||
throw new InvalidOperationException("Model must be fitted before prediction."); | ||
} | ||
|
||
return xValues.Select(Predict).ToList(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.