-
-
Notifications
You must be signed in to change notification settings - Fork 48.5k
Add vectorized implementations of Linear Regression using Gradient Descent #13221
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
Open
somrita-banerjee
wants to merge
21
commits into
TheAlgorithms:master
Choose a base branch
from
somrita-banerjee:issue/logistic_regression
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
10a0274
Add naive and vectorized implementations of Linear Regression using G…
somrita-banerjee 11fa072
Add references section to docstrings in linear regression implementat…
somrita-banerjee e879c47
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d868aba
Refactor function signatures for improved readability in linear regre…
somrita-banerjee 91cbc22
Refactor function parameters and improve logging format in gradient d…
somrita-banerjee 260f5a6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 80082fd
Refactor function signatures for improved readability in linear regre…
somrita-banerjee bda36ee
Merge branch 'issue/logistic_regression' of https://github.com/somrit…
somrita-banerjee ebf3ab2
Update README sections for dataset inputs and usage instructions in l…
somrita-banerjee 7375f39
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 8d33d90
Add doctests for dataset collection and gradient descent functions
somrita-banerjee e07322d
Merge branch 'issue/logistic_regression' of https://github.com/somrit…
somrita-banerjee 2e6804d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4db85f5
Refactor imports and improve README formatting in linear regression s…
somrita-banerjee 6c3e951
fix doctests
somrita-banerjee 9c18a51
Remove linear regression naive implementation script
somrita-banerjee 6551ba6
Refactor docstring and improve script documentation for clarity
somrita-banerjee 1d46f38
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] acc7978
Fix formatting in gradient_descent doctest and streamline main functi…
somrita-banerjee 8dc5a93
Merge branch 'issue/logistic_regression' of https://github.com/somrit…
somrita-banerjee acd2f67
fix doctest
somrita-banerjee 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,150 @@ | ||
""" | ||
Naive implementation of Linear Regression using Gradient Descent. | ||
|
||
This version is intentionally less optimized and more verbose, | ||
designed for educational clarity. It shows the step-by-step | ||
gradient descent update and error calculation. | ||
|
||
Dataset used: CSGO dataset (ADR vs Rating) | ||
|
||
References: | ||
https://en.wikipedia.org/wiki/Linear_regression | ||
""" | ||
|
||
# /// script | ||
# requires-python = ">=3.13" | ||
# dependencies = [ | ||
# "httpx", | ||
# "numpy", | ||
# ] | ||
# /// | ||
|
||
import httpx | ||
import numpy as np | ||
|
||
|
||
def collect_dataset() -> np.ndarray: | ||
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
"""Collect dataset of CSGO (ADR vs Rating) | ||
|
||
:return: dataset as numpy matrix | ||
""" | ||
response = httpx.get( | ||
"https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/" | ||
"master/Week1/ADRvsRating.csv", | ||
timeout=10, | ||
) | ||
lines = response.text.splitlines() | ||
data = [line.split(",") for line in lines] | ||
data.pop(0) # remove header row | ||
dataset = np.matrix(data) | ||
return dataset | ||
|
||
|
||
def run_steep_gradient_descent( | ||
data_x: np.ndarray, data_y: np.ndarray, len_data: int, alpha: float, theta: np.ndarray | ||
) -> np.ndarray: | ||
"""Run one step of steep gradient descent. | ||
|
||
:param data_x: dataset features | ||
:param data_y: dataset labels | ||
:param len_data: number of samples | ||
:param alpha: learning rate | ||
:param theta: feature vector (weights) | ||
|
||
:return: updated theta | ||
|
||
>>> import numpy as np | ||
>>> data_x = np.array([[1, 2], [3, 4]]) | ||
>>> data_y = np.array([5, 6]) | ||
>>> len_data = len(data_x) | ||
>>> alpha = 0.01 | ||
>>> theta = np.array([0.1, 0.2]) | ||
>>> run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) | ||
array([0.196, 0.343]) | ||
""" | ||
prod = np.dot(theta, data_x.T) | ||
prod -= data_y.T | ||
grad = np.dot(prod, data_x) | ||
theta = theta - (alpha / len_data) * grad | ||
return theta | ||
|
||
|
||
def sum_of_square_error( | ||
data_x: np.ndarray, | ||
data_y: np.ndarray, | ||
len_data: int, | ||
theta: np.ndarray | ||
) -> float: | ||
"""Return sum of square error for error calculation. | ||
|
||
>>> vc_x = np.array([[1.1], [2.1], [3.1]]) | ||
>>> vc_y = np.array([1.2, 2.2, 3.2]) | ||
>>> round(sum_of_square_error(vc_x, vc_y, 3, np.array([1])), 3) | ||
0.005 | ||
""" | ||
prod = np.dot(theta, data_x.T) | ||
prod -= data_y.T | ||
error = np.sum(np.square(prod)) / (2 * len_data) | ||
return float(error) | ||
|
||
|
||
def run_linear_regression( | ||
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
data_x: np.ndarray, | ||
data_y: np.ndarray | ||
) -> np.ndarray: | ||
"""Run linear regression using gradient descent. | ||
|
||
:param data_x: dataset features | ||
:param data_y: dataset labels | ||
:return: learned feature vector theta | ||
""" | ||
iterations = 100000 | ||
alpha = 0.000155 | ||
|
||
no_features = data_x.shape[1] | ||
len_data = data_x.shape[0] - 1 | ||
|
||
theta = np.zeros((1, no_features)) | ||
|
||
for i in range(iterations): | ||
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) | ||
error = sum_of_square_error(data_x, data_y, len_data, theta) | ||
print(f"Iteration {i + 1}: Error = {error:.5f}") | ||
|
||
return theta | ||
|
||
|
||
def mean_absolute_error( | ||
predicted_y: np.ndarray, | ||
original_y: np.ndarray | ||
) -> float: | ||
"""Return mean absolute error. | ||
|
||
>>> predicted_y = np.array([3, -0.5, 2, 7]) | ||
>>> original_y = np.array([2.5, 0.0, 2, 8]) | ||
>>> mean_absolute_error(predicted_y, original_y) | ||
0.5 | ||
""" | ||
total = sum(abs(y - predicted_y[i]) for i, y in enumerate(original_y)) | ||
return total / len(original_y) | ||
|
||
|
||
def main() -> None: | ||
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
"""Driver function.""" | ||
data = collect_dataset() | ||
|
||
len_data = data.shape[0] | ||
data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) | ||
data_y = data[:, -1].astype(float) | ||
|
||
theta = run_linear_regression(data_x, data_y) | ||
print("Resultant Feature vector:") | ||
for value in theta.ravel(): | ||
print(f"{value:.5f}") | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() | ||
main() |
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,98 @@ | ||
""" | ||
Vectorized implementation of Linear Regression using Gradient Descent. | ||
|
||
This version uses NumPy vectorization for efficiency. | ||
It is faster and cleaner than the naive version but assumes | ||
readers are familiar with matrix operations. | ||
|
||
Dataset used: CSGO dataset (ADR vs Rating) | ||
|
||
References: | ||
https://en.wikipedia.org/wiki/Linear_regression | ||
""" | ||
|
||
# /// script | ||
# requires-python = ">=3.13" | ||
# dependencies = [ | ||
# "httpx", | ||
# "numpy", | ||
# ] | ||
# /// | ||
|
||
import httpx | ||
import numpy as np | ||
|
||
|
||
def collect_dataset() -> np.ndarray: | ||
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Collect dataset of CSGO (ADR vs Rating). | ||
|
||
:return: dataset as numpy array | ||
""" | ||
response = httpx.get( | ||
"https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/" | ||
"master/Week1/ADRvsRating.csv", | ||
timeout=10, | ||
) | ||
lines = response.text.splitlines() | ||
data = [line.split(",") for line in lines] | ||
data.pop(0) # remove header row | ||
return np.array(data, dtype=float) | ||
|
||
|
||
def gradient_descent( | ||
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
x: np.ndarray, y: np.ndarray, alpha: float = 0.000155, iterations: int = 100000 | ||
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
) -> np.ndarray: | ||
"""Run gradient descent in a fully vectorized form. | ||
|
||
:param x: dataset features | ||
:param y: dataset labels | ||
:param alpha: learning rate | ||
:param iterations: number of iterations | ||
:return: learned feature vector theta | ||
""" | ||
m, n = x.shape | ||
theta = np.zeros((n, 1)) | ||
|
||
for i in range(iterations): | ||
predictions = x @ theta | ||
errors = predictions - y | ||
gradients = (x.T @ errors) / m | ||
theta -= alpha * gradients | ||
|
||
if i % (iterations // 10) == 0: # log occasionally | ||
cost = np.sum(errors**2) / (2 * m) | ||
print(f"Iteration {i + 1}: Error = {cost:.5f}") | ||
|
||
return theta | ||
|
||
|
||
def mean_absolute_error(predicted_y: np.ndarray, original_y: np.ndarray) -> float: | ||
"""Return mean absolute error. | ||
|
||
>>> pred = np.array([3, -0.5, 2, 7]) | ||
>>> orig = np.array([2.5, 0.0, 2, 8]) | ||
>>> mean_absolute_error(pred, orig) | ||
0.5 | ||
""" | ||
return float(np.mean(np.abs(original_y - predicted_y))) | ||
|
||
|
||
def main() -> None: | ||
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
somrita-banerjee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Driver function.""" | ||
dataset = collect_dataset() | ||
|
||
m = dataset.shape[0] | ||
x = np.c_[np.ones(m), dataset[:, :-1]] # add intercept term | ||
y = dataset[:, -1].reshape(-1, 1) | ||
|
||
theta = gradient_descent(x, y) | ||
print("Resultant Feature vector:") | ||
for value in theta.ravel(): | ||
print(f"{value:.5f}") | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() | ||
main() |
Oops, something went wrong.
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.