MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / binary_focal_cross_entropy

Function binary_focal_cross_entropy

machine_learning/loss_functions.py:42–90  ·  view source on GitHub ↗

Calculate the mean binary focal cross-entropy (BFCE) loss between true labels and predicted probabilities. BFCE loss quantifies dissimilarity between true labels (0 or 1) and predicted probabilities. It's a variation of binary cross-entropy that addresses class imbalance by foc

(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    gamma: float = 2.0,
    alpha: float = 0.25,
    epsilon: float = 1e-15,
)

Source from the content-addressed store, hash-verified

40
41
42def binary_focal_cross_entropy(
43 y_true: np.ndarray,
44 y_pred: np.ndarray,
45 gamma: float = 2.0,
46 alpha: float = 0.25,
47 epsilon: float = 1e-15,
48) -> float:
49 """
50 Calculate the mean binary focal cross-entropy (BFCE) loss between true labels
51 and predicted probabilities.
52
53 BFCE loss quantifies dissimilarity between true labels (0 or 1) and predicted
54 probabilities. It's a variation of binary cross-entropy that addresses class
55 imbalance by focusing on hard examples.
56
57 BCFE = -Σ(alpha * (1 - y_pred)**gamma * y_true * log(y_pred)
58 + (1 - alpha) * y_pred**gamma * (1 - y_true) * log(1 - y_pred))
59
60 Reference: [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf)
61
62 Parameters:
63 - y_true: True binary labels (0 or 1).
64 - y_pred: Predicted probabilities for class 1.
65 - gamma: Focusing parameter for modulating the loss (default: 2.0).
66 - alpha: Weighting factor for class 1 (default: 0.25).
67 - epsilon: Small constant to avoid numerical instability.
68
69 >>> true_labels = np.array([0, 1, 1, 0, 1])
70 >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8])
71 >>> float(binary_focal_cross_entropy(true_labels, predicted_probs))
72 0.008257977659239775
73 >>> true_labels = np.array([0, 1, 1, 0, 1])
74 >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])
75 >>> binary_focal_cross_entropy(true_labels, predicted_probs)
76 Traceback (most recent call last):
77 ...
78 ValueError: Input arrays must have the same length.
79 """
80 if len(y_true) != len(y_pred):
81 raise ValueError("Input arrays must have the same length.")
82 # Clip predicted probabilities to avoid log(0)
83 y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
84
85 bcfe_loss = -(
86 alpha * (1 - y_pred) ** gamma * y_true * np.log(y_pred)
87 + (1 - alpha) * y_pred**gamma * (1 - y_true) * np.log(1 - y_pred)
88 )
89
90 return np.mean(bcfe_loss)
91
92
93def categorical_cross_entropy(

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected