Skip to content

Commit dc3129b

Browse files
Merge pull request #1 from THEGAMECHANGER416/THEGAMECHANGER416-patch-1
Create categorical_cross_entropy.py
2 parents ed19b1c + 4893c31 commit dc3129b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Categorical Cross-Entropy Loss
3+
4+
This function calculates the Categorical Cross-Entropy Loss between true class
5+
labels and predicted class probabilities.
6+
7+
Formula:
8+
Categorical Cross-Entropy Loss = -Σ(y_true * log(y_pred))
9+
10+
Resources:
11+
- [Wikipedia - Cross entropy](https://en.wikipedia.org/wiki/Cross_entropy)
12+
"""
13+
14+
import numpy as np
15+
16+
def categorical_crossentropy(
17+
y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15
18+
) -> float:
19+
"""
20+
Calculate Categorical Cross-Entropy Loss between true class labels and
21+
predicted class probabilities.
22+
23+
Parameters:
24+
- y_true: True class labels (one-hot encoded) as a NumPy array.
25+
- y_pred: Predicted class probabilities as a NumPy array.
26+
- epsilon: Small constant to avoid numerical instability.
27+
28+
Returns:
29+
- ce_loss: Categorical Cross-Entropy Loss as a floating-point number.
30+
31+
Example:
32+
>>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
33+
>>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]])
34+
>>> categorical_crossentropy(true_labels, pred_probs)
35+
0.18913199175146167
36+
37+
>>> y_true = np.array([[1, 0], [0, 1]])
38+
>>> y_pred = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])
39+
>>> categorical_crossentropy(y_true, y_pred)
40+
Traceback (most recent call last):
41+
...
42+
ValueError: Input arrays must have the same length.
43+
"""
44+
if y_true.shape != y_pred.shape:
45+
raise ValueError("Input arrays must have the same length.")
46+
47+
# Clip predicted probabilities to avoid log(0)
48+
y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
49+
50+
# Calculate categorical cross-entropy loss
51+
return -np.sum(y_true * np.log(y_pred)) / len(y_true)
52+
53+
if __name__ == "__main__":
54+
import doctest
55+
doctest.testmod()

0 commit comments

Comments
 (0)