-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Added categorical_crossentropy loss function #10152
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
tianyizheng02
merged 14 commits into
TheAlgorithms:master
from
THEGAMECHANGER416:master
Oct 10, 2023
Merged
Changes from 10 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4893c31
Create categorical_cross_entropy.py
THEGAMECHANGER416 dc3129b
Merge pull request #1 from THEGAMECHANGER416/THEGAMECHANGER416-patch-1
THEGAMECHANGER416 35fa3f3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 341df18
Update machine_learning/loss_functions/categorical_cross_entropy.py
THEGAMECHANGER416 b673376
Update categorical_cross_entropy.py
THEGAMECHANGER416 06110d9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1cff490
Update categorical_cross_entropy.py
THEGAMECHANGER416 65c4702
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] eeb0bc6
Update machine_learning/loss_functions/categorical_cross_entropy.py
THEGAMECHANGER416 c60aad4
Update machine_learning/loss_functions/categorical_cross_entropy.py
THEGAMECHANGER416 e194822
Update machine_learning/loss_functions/categorical_cross_entropy.py
THEGAMECHANGER416 f163f47
Update machine_learning/loss_functions/categorical_cross_entropy.py
THEGAMECHANGER416 cef2b27
Update categorical_cross_entropy.py
THEGAMECHANGER416 94bb4ce
[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
85 changes: 85 additions & 0 deletions
85
machine_learning/loss_functions/categorical_cross_entropy.py
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,85 @@ | ||
""" | ||
Categorical Cross-Entropy Loss | ||
|
||
This function calculates the Categorical Cross-Entropy Loss between true class | ||
labels and predicted class probabilities. | ||
|
||
Formula: | ||
Categorical Cross-Entropy Loss = -Σ(y_true * log(y_pred)) | ||
|
||
Resources: | ||
- [Wikipedia - Cross entropy](https://en.wikipedia.org/wiki/Cross_entropy) | ||
""" | ||
|
||
import numpy as np | ||
|
||
|
||
def categorical_cross_entropy( | ||
y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 | ||
) -> float: | ||
""" | ||
Calculate Categorical Cross-Entropy Loss between true class labels and | ||
predicted class probabilities. | ||
|
||
Parameters: | ||
- y_true: True class labels (one-hot encoded) as a NumPy array. | ||
THEGAMECHANGER416 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- y_pred: Predicted class probabilities as a NumPy array. | ||
- epsilon: Small constant to avoid numerical instability. | ||
|
||
Returns: | ||
- ce_loss: Categorical Cross-Entropy Loss as a floating-point number. | ||
|
||
Example: | ||
>>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) | ||
>>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]]) | ||
>>> categorical_cross_entropy(true_labels, pred_probs) | ||
0.567395975254385 | ||
|
||
>>> y_true = np.array([[1, 0], [0, 1]]) | ||
>>> y_pred = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) | ||
>>> categorical_cross_entropy(y_true, y_pred) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: Input arrays must have the same shape. | ||
|
||
>>> y_true = np.array([[2, 0, 1], [1, 0, 0]]) | ||
>>> y_pred = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) | ||
>>> categorical_cross_entropy(y_true, y_pred) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: y_true must be one-hot encoded. | ||
|
||
THEGAMECHANGER416 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
>>> y_true = np.array([[1, 0, 1], [1, 0, 0]]) | ||
>>> y_pred = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]]) | ||
>>> categorical_cross_entropy(y_true, y_pred) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: y_true must be one-hot encoded. | ||
|
||
>>> y_true = np.array([[1, 0, 0], [0, 1, 0]]) | ||
>>> y_pred = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]]) | ||
>>> categorical_cross_entropy(y_true, y_pred) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: Predicted probabilities must sum to approximately 1. | ||
""" | ||
if y_true.shape != y_pred.shape: | ||
raise ValueError("Input arrays must have the same shape.") | ||
|
||
if not np.array_equal(y_true[y_true != 0], [1]): | ||
THEGAMECHANGER416 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raise ValueError("y_true must be one-hot encoded.") | ||
|
||
if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)): | ||
raise ValueError("Predicted probabilities must sum to approximately 1.") | ||
|
||
# Clip predicted probabilities to avoid log(0) | ||
y_pred = np.clip(y_pred, epsilon, 1 - epsilon) | ||
THEGAMECHANGER416 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# Calculate categorical cross-entropy loss | ||
return -np.sum(y_true * np.log(y_pred)) | ||
|
||
|
||
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.