-
-
Notifications
You must be signed in to change notification settings - Fork 51.1k
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
Merged
cclauss
merged 24 commits into
TheAlgorithms:master
from
somrita-banerjee:issue/logistic_regression
Sep 11, 2026
+113
−0
Merged
Changes from 12 commits
Commits
Show all changes
24 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 bbe57f0
Merge branch 'master' into issue/logistic_regression
cclauss 44da857
updating DIRECTORY.md
cclauss 97589e8
Change httpx to httpx2 and update docstring
cclauss 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,181 @@ | ||
| """README, Author - Somrita Banerjee(mailto:somritabanerjee126@gmail.com) | ||
| Requirements: | ||
| - Python >= 3.13 | ||
| - httpx | ||
| - numpy | ||
|
|
||
| Inputs: | ||
| - Downloads a CSV dataset (ADR vs Rating) from a public GitHub URL. | ||
| - The dataset should have features in all columns except the last, which is the label. | ||
|
|
||
| Usage: | ||
| - Run this script directly: | ||
| python linear_regression_naive.py | ||
| - The script will fetch the dataset, run linear regression using gradient descent, and print the learned feature vector (theta) and error at each iteration. | ||
|
|
||
| """ | ||
|
|
||
| """ | ||
| 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
somrita-banerjee marked this conversation as resolved.
Outdated
|
||
| """Collect dataset of CSGO (ADR vs Rating) | ||
|
|
||
| :return: dataset as numpy matrix | ||
|
|
||
| >>> ds = collect_dataset() | ||
| >>> isinstance(ds, np.matrix) | ||
| True | ||
| >>> ds.shape[1] >= 2 | ||
| True | ||
| """ | ||
| 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(data_x: np.ndarray, data_y: np.ndarray) -> np.ndarray: | ||
|
somrita-banerjee marked this conversation as resolved.
Outdated
somrita-banerjee marked this conversation as resolved.
Outdated
|
||
| """Run linear regression using gradient descent. | ||
|
|
||
| :param data_x: dataset features | ||
| :param data_y: dataset labels | ||
| :return: learned feature vector theta | ||
|
|
||
| >>> import numpy as np | ||
| >>> x = np.array([[1, 1], [1, 2], [1, 3]]) | ||
| >>> y = np.array([1, 2, 3]) | ||
| >>> theta = run_linear_regression(x, y) | ||
| Iteration 1: Error = ... | ||
| ... # lots of output omitted | ||
| >>> theta.shape | ||
| (1, 2) | ||
| >>> abs(theta[0, 0] - 0) < 0.1 # intercept close to 0 | ||
| True | ||
| >>> abs(theta[0, 1] - 1) < 0.1 # slope close to 1 | ||
| True | ||
| """ | ||
| 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(predicted_y[i] - y) for i, y in enumerate(original_y)) | ||
| return total / len(original_y) | ||
|
|
||
|
|
||
| def main() -> None: | ||
|
somrita-banerjee marked this conversation as resolved.
Outdated
somrita-banerjee marked this conversation as resolved.
Outdated
somrita-banerjee marked this conversation as resolved.
Outdated
somrita-banerjee marked this conversation as resolved.
Outdated
somrita-banerjee marked this conversation as resolved.
Outdated
|
||
| """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,137 @@ | ||
| """README, Author - Somrita Banerjee(mailto:somritabanerjee126@gmail.com) | ||
| Requirements: | ||
| - Python >= 3.13 | ||
| - httpx | ||
| - numpy | ||
|
|
||
| Inputs: | ||
| - The script automatically downloads a CSV dataset (ADR vs Rating) from a public GitHub URL. | ||
| - The dataset must have features in all columns except the last, which is the label (rating). | ||
|
|
||
| Usage: | ||
| - Run this script directly: | ||
| python linear_regression_vectorized.py | ||
| - The script will fetch the dataset, run linear regression using gradient descent, and print the learned feature vector (theta) and error at intervals. | ||
|
|
||
| """ | ||
|
|
||
| """ | ||
| 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.
somrita-banerjee marked this conversation as resolved.
somrita-banerjee marked this conversation as resolved.
|
||
| """Collect dataset of CSGO (ADR vs Rating). | ||
|
|
||
| :return: dataset as numpy array | ||
|
|
||
| >>> ds = collect_dataset() | ||
| >>> isinstance(ds, np.ndarray) | ||
| True | ||
| >>> ds.shape[1] >= 2 | ||
| True | ||
| """ | ||
| 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.
somrita-banerjee marked this conversation as resolved.
somrita-banerjee marked this conversation as resolved.
|
||
| features: np.ndarray, labels: np.ndarray, alpha: float = 0.000155, iterations: int = 100000 | ||
| ) -> np.ndarray: | ||
| """Run gradient descent in a fully vectorized form. | ||
|
|
||
| :param features: dataset features | ||
| :param labels: dataset labels | ||
| :param alpha: learning rate | ||
| :param iterations: number of iterations | ||
| :return: learned feature vector theta | ||
|
|
||
| >>> import numpy as np | ||
| >>> features = np.array([[1, 1], [1, 2], [1, 3]]) | ||
| >>> labels = np.array([[1], [2], [3]]) | ||
| >>> theta = gradient_descent(features, labels, alpha=0.01, iterations=1000) | ||
| Iteration 1: Error = ... | ||
| ... # output omitted | ||
| >>> theta.shape | ||
| (2, 1) | ||
| >>> abs(theta[0, 0] - 0) < 0.1 # intercept close to 0 | ||
| True | ||
| >>> abs(theta[1, 0] - 1) < 0.1 # slope close to 1 | ||
| True | ||
| """ | ||
| m, n = features.shape | ||
| theta = np.zeros((n, 1)) | ||
|
|
||
| for i in range(iterations): | ||
| predictions = features @ theta | ||
| errors = predictions - labels | ||
| gradients = (features.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.
somrita-banerjee marked this conversation as resolved.
somrita-banerjee marked this conversation as resolved.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file |
||
| """Driver function. | ||
|
|
||
| >>> main() # doctest: +SKIP | ||
| """ | ||
| dataset = collect_dataset() | ||
|
|
||
| m = dataset.shape[0] | ||
| features = np.c_[np.ones(m), dataset[:, :-1]] # add intercept term | ||
| labels = dataset[:, -1].reshape(-1, 1) | ||
|
|
||
| theta = gradient_descent(features, labels) | ||
| 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.