-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Added Gradient Boosting Classifier #10944
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 7 commits into
TheAlgorithms:master
from
SannketNikam:gradient-boosting-classifier
Oct 27, 2023
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ce540c7
Added Gradient Boosting Classifier
SannketNikam 171a42c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ec6ed8c
Update gradient_boosting_classifier.py
SannketNikam 0cbc5a5
Update gradient_boosting_classifier.py
SannketNikam 6661e12
Update gradient_boosting_classifier.py
SannketNikam 63bcd54
Update gradient_boosting_classifier.py
SannketNikam 3af39b5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 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,95 @@ | ||
|
||
import numpy as np | ||
from sklearn.datasets import load_iris | ||
from sklearn.metrics import accuracy_score | ||
from sklearn.model_selection import train_test_split | ||
from sklearn.tree import DecisionTreeRegressor | ||
|
||
|
||
class GradientBoostingClassifier: | ||
def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None: | ||
""" | ||
Initialize a GradientBoostingClassifier. | ||
|
||
Parameters: | ||
- n_estimators (int): The number of weak learners to train. | ||
- learning_rate (float): The learning rate for updating the model. | ||
|
||
Attributes: | ||
- n_estimators (int): The number of weak learners. | ||
- learning_rate (float): The learning rate. | ||
- models (list): A list to store the trained weak learners. | ||
""" | ||
self.n_estimators = n_estimators | ||
self.learning_rate = learning_rate | ||
self.models: list[tuple[DecisionTreeRegressor, float]] = [] | ||
|
||
def fit(self, x: np.ndarray, y: np.ndarray) -> None: | ||
""" | ||
Fit the GradientBoostingClassifier to the training data. | ||
|
||
Parameters: | ||
- x (np.ndarray): The training features. | ||
- y (np.ndarray): The target values. | ||
|
||
Returns: | ||
None | ||
""" | ||
for _ in range(self.n_estimators): | ||
# Calculate the pseudo-residuals | ||
residuals = -self.gradient(y, self.predict(x)) | ||
# Fit a weak learner (e.g., decision tree) to the residuals | ||
model = DecisionTreeRegressor(max_depth=1) | ||
model.fit(x, residuals) | ||
# Update the model by adding the weak learner with a learning rate | ||
self.models.append((model, self.learning_rate)) | ||
|
||
def predict(self, x: np.ndarray) -> np.ndarray: | ||
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Make predictions on input data. | ||
|
||
Parameters: | ||
- x (np.ndarray): The input data for making predictions. | ||
|
||
Returns: | ||
- np.ndarray: An array of binary predictions (-1 or 1). | ||
""" | ||
# Initialize predictions with zeros | ||
predictions = np.zeros(x.shape[0]) | ||
for model, learning_rate in self.models: | ||
predictions += learning_rate * model.predict(x) | ||
return np.sign(predictions) # Convert to binary predictions (-1 or 1) | ||
|
||
def gradient(self, y: np.ndarray, y_pred: np.ndarray) -> np.ndarray: | ||
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Calculate the negative gradient (pseudo-residuals) for logistic loss. | ||
|
||
Parameters: | ||
- y (np.ndarray): The target values. | ||
- y_pred (np.ndarray): The predicted values. | ||
|
||
Returns: | ||
- np.ndarray: An array of pseudo-residuals. | ||
""" | ||
return -y / (1 + np.exp(y * y_pred)) | ||
|
||
|
||
if __name__ == "__main__": | ||
iris = load_iris() | ||
X, y = iris.data, iris.target | ||
X_train, X_test, y_train, y_test = train_test_split( | ||
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
SannketNikam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
X, y, test_size=0.2, random_state=42 | ||
) | ||
|
||
clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1) | ||
clf.fit(X_train, y_train) | ||
|
||
y_pred = clf.predict(X_test) | ||
accuracy = accuracy_score(y_test, y_pred) | ||
print(f"Accuracy: {accuracy:.2f}") | ||
|
||
# Perform some calculations in doctests | ||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() |
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.