-
-
Notifications
You must be signed in to change notification settings - Fork 49.6k
add: Perceptron algorithm implementation #14022
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
SaviNimz
wants to merge
5
commits into
TheAlgorithms:master
Choose a base branch
from
SaviNimz:feature/add-perceptron
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 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
487564d
add: Perceptron algorithm implementation
SaviNimz cba3b02
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 723908e
fixed the linting errors
SaviNimz fe4b10e
add: Perceptron algorithm in machine_learning
SaviNimz e73ffce
added readable variable names
SaviNimz 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,131 @@ | ||
| """ | ||
| Perceptron Algorithm Implementation | ||
| """ | ||
|
|
||
| import numpy as np | ||
|
|
||
|
|
||
| class Perceptron: | ||
| """ | ||
| Perceptron Classifier | ||
|
|
||
| Parameters: | ||
| ----------- | ||
| learning_rate : float | ||
| Learning rate (between 0.0 and 1.0) | ||
| epochs : int | ||
| Passes over the training dataset. | ||
|
|
||
| Attributes: | ||
| ----------- | ||
| weights : numpy.ndarray | ||
| Weights after fitting. | ||
| bias : float | ||
| Bias unit after fitting. | ||
| errors : list | ||
| Number of misclassifications (updates) in each epoch. | ||
|
|
||
| Examples: | ||
| --------- | ||
| >>> import numpy as np | ||
| >>> samples = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) | ||
| >>> y = np.array([0, 0, 0, 1]) | ||
| >>> perceptron = Perceptron(learning_rate=0.1, epochs=10) | ||
| >>> _ = perceptron.fit(samples, y) | ||
| >>> perceptron.predict(samples).tolist() | ||
| [0, 0, 0, 1] | ||
| """ | ||
|
|
||
| def __init__(self, learning_rate: float = 0.01, epochs: int = 1000) -> None: | ||
| self.learning_rate = learning_rate | ||
| self.epochs = epochs | ||
| self.weights = np.zeros(1) | ||
| self.bias = 0.0 | ||
| self.errors: list[int] = [] | ||
|
|
||
| def fit(self, samples: np.ndarray, y: np.ndarray) -> "Perceptron": | ||
SaviNimz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Fit training data. | ||
|
|
||
| Parameters: | ||
| ----------- | ||
| samples : shape = [n_samples, n_features] | ||
| Training vectors, where n_samples is the number of samples | ||
| and n_features is the number of features. | ||
| y : shape = [n_samples] | ||
| Target values. | ||
|
|
||
| Returns: | ||
| -------- | ||
| self : object | ||
|
|
||
| Examples: | ||
| --------- | ||
| >>> import numpy as np | ||
| >>> samples = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) | ||
| >>> y = np.array([0, 0, 0, 1]) | ||
| >>> perceptron = Perceptron(learning_rate=0.1, epochs=10) | ||
| >>> _ = perceptron.fit(samples, y) | ||
| """ | ||
| _, n_features = samples.shape | ||
| self.weights = np.zeros(n_features) | ||
| self.bias = 0.0 | ||
| self.errors = [] | ||
|
|
||
| for _ in range(self.epochs): | ||
| errors = 0 | ||
| for xi, target in zip(samples, y): | ||
| # Calculate update | ||
| update = self.learning_rate * (target - self.predict(xi)) | ||
| self.weights += update * xi | ||
| self.bias += update | ||
| errors += int(update != 0.0) | ||
| self.errors.append(errors) | ||
| return self | ||
|
|
||
| def predict(self, samples: np.ndarray) -> np.ndarray: | ||
| """ | ||
| Return class label after unit step | ||
|
|
||
| Examples: | ||
| --------- | ||
| >>> import numpy as np | ||
| >>> samples = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) | ||
| >>> y = np.array([0, 0, 0, 1]) | ||
| >>> perceptron = Perceptron(learning_rate=0.1, epochs=10) | ||
| >>> _ = perceptron.fit(samples, y) | ||
| >>> perceptron.predict(samples).tolist() | ||
| [0, 0, 0, 1] | ||
| """ | ||
| linear_output = np.dot(samples, self.weights) + self.bias | ||
| return self.activation_function(linear_output) | ||
|
|
||
| def activation_function(self, x: np.ndarray) -> np.ndarray: | ||
SaviNimz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
SaviNimz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Step activation function: returns 1 if x >= 0, else 0 | ||
|
|
||
| Examples: | ||
| --------- | ||
| >>> import numpy as np | ||
| >>> perceptron = Perceptron() | ||
| >>> perceptron.activation_function(np.array([0.5, -0.5, 0])).tolist() | ||
| [1, 0, 1] | ||
| """ | ||
| return np.where(x >= 0, 1, 0) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import doctest | ||
|
|
||
| doctest.testmod() | ||
|
|
||
| # Example usage | ||
| samples = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) | ||
| y = np.array([0, 0, 0, 1]) # AND gate | ||
|
|
||
| perceptron = Perceptron(learning_rate=0.1, epochs=10) | ||
| perceptron.fit(samples, y) | ||
|
|
||
| print("Weights:", perceptron.weights) | ||
| print("Bias:", perceptron.bias) | ||
| print("Predictions:", perceptron.predict(samples)) | ||
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.