-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add Logistic Regression Algorithm for Machine Learning #540
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 3 commits into
TheAlgorithms:master
from
ngtduc693:feature/logistic-regression
Oct 5, 2025
+153
−0
Merged
Changes from all commits
Commits
Show all changes
3 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
65 changes: 65 additions & 0 deletions
65
Algorithms.Tests/MachineLearning/LogisticRegressionTests.cs
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,65 @@ | ||
using NUnit.Framework; | ||
using Algorithms.MachineLearning; | ||
using System; | ||
|
||
namespace Algorithms.Tests.MachineLearning; | ||
|
||
[TestFixture] | ||
public class LogisticRegressionTests | ||
{ | ||
[Test] | ||
public void Fit_ThrowsOnEmptyInput() | ||
{ | ||
var model = new LogisticRegression(); | ||
Assert.Throws<ArgumentException>(() => model.Fit(Array.Empty<double[]>(), Array.Empty<int>())); | ||
} | ||
|
||
[Test] | ||
public void Fit_ThrowsOnMismatchedLabels() | ||
{ | ||
var model = new LogisticRegression(); | ||
double[][] X = { new double[] { 1, 2 } }; | ||
int[] y = { 1, 0 }; | ||
Assert.Throws<ArgumentException>(() => model.Fit(X, y)); | ||
} | ||
|
||
[Test] | ||
public void FitAndPredict_WorksOnSimpleData() | ||
{ | ||
// Simple AND logic | ||
double[][] X = | ||
{ | ||
new[] { 0.0, 0.0 }, | ||
new[] { 0.0, 1.0 }, | ||
new[] { 1.0, 0.0 }, | ||
new[] { 1.0, 1.0 } | ||
}; | ||
int[] y = { 0, 0, 0, 1 }; | ||
var model = new LogisticRegression(); | ||
model.Fit(X, y, epochs: 2000, learningRate: 0.1); | ||
Assert.That(model.Predict(new double[] { 0, 0 }), Is.EqualTo(0)); | ||
Assert.That(model.Predict(new double[] { 0, 1 }), Is.EqualTo(0)); | ||
Assert.That(model.Predict(new double[] { 1, 0 }), Is.EqualTo(0)); | ||
Assert.That(model.Predict(new double[] { 1, 1 }), Is.EqualTo(1)); | ||
} | ||
|
||
[Test] | ||
public void PredictProbability_ThrowsOnFeatureMismatch() | ||
{ | ||
var model = new LogisticRegression(); | ||
double[][] X = { new double[] { 1, 2 } }; | ||
int[] y = { 1 }; | ||
model.Fit(X, y); | ||
Assert.Throws<ArgumentException>(() => model.PredictProbability(new double[] { 1 })); | ||
} | ||
|
||
[Test] | ||
public void FeatureCount_ReturnsCorrectValue() | ||
{ | ||
var model = new LogisticRegression(); | ||
double[][] X = { new double[] { 1, 2, 3 } }; | ||
int[] y = { 1 }; | ||
model.Fit(X, y); | ||
Assert.That(model.FeatureCount, Is.EqualTo(3)); | ||
} | ||
} |
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,87 @@ | ||
using System; | ||
using System.Linq; | ||
|
||
namespace Algorithms.MachineLearning; | ||
|
||
/// <summary> | ||
/// Logistic Regression for binary classification. | ||
/// </summary> | ||
public class LogisticRegression | ||
{ | ||
private double[] weights = []; | ||
private double bias; | ||
|
||
public int FeatureCount => weights.Length; | ||
|
||
/// <summary> | ||
/// Fit the model using gradient descent. | ||
/// </summary> | ||
/// <param name="x">2D array of features (samples x features).</param> | ||
/// <param name="y">Array of labels (0 or 1).</param> | ||
/// <param name="epochs">Number of iterations.</param> | ||
/// <param name="learningRate">Step size.</param> | ||
public void Fit(double[][] x, int[] y, int epochs = 1000, double learningRate = 0.01) | ||
{ | ||
if (x.Length == 0 || x[0].Length == 0) | ||
{ | ||
throw new ArgumentException("Input features cannot be empty."); | ||
} | ||
|
||
if (x.Length != y.Length) | ||
{ | ||
throw new ArgumentException("Number of samples and labels must match."); | ||
} | ||
|
||
int nSamples = x.Length; | ||
int nFeatures = x[0].Length; | ||
weights = new double[nFeatures]; | ||
bias = 0; | ||
|
||
for (int epoch = 0; epoch < epochs; epoch++) | ||
{ | ||
double[] dw = new double[nFeatures]; | ||
double db = 0; | ||
for (int i = 0; i < nSamples; i++) | ||
{ | ||
double linear = Dot(x[i], weights) + bias; | ||
double pred = Sigmoid(linear); | ||
double error = pred - y[i]; | ||
for (int j = 0; j < nFeatures; j++) | ||
{ | ||
dw[j] += error * x[i][j]; | ||
} | ||
|
||
db += error; | ||
} | ||
|
||
for (int j = 0; j < nFeatures; j++) | ||
{ | ||
weights[j] -= learningRate * dw[j] / nSamples; | ||
} | ||
|
||
bias -= learningRate * db / nSamples; | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Predict probability for a single sample. | ||
/// </summary> | ||
public double PredictProbability(double[] x) | ||
{ | ||
if (x.Length != weights.Length) | ||
{ | ||
throw new ArgumentException("Feature count mismatch."); | ||
} | ||
|
||
return Sigmoid(Dot(x, weights) + bias); | ||
} | ||
|
||
/// <summary> | ||
/// Predict class label (0 or 1) for a single sample. | ||
/// </summary> | ||
public int Predict(double[] x) => PredictProbability(x) >= 0.5 ? 1 : 0; | ||
|
||
private static double Sigmoid(double z) => 1.0 / (1.0 + Math.Exp(-z)); | ||
siriak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private static double Dot(double[] a, double[] b) => a.Zip(b).Sum(pair => pair.First * pair.Second); | ||
} |
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.