The interview problem

Practice prompt

A binary classifier trains on many easy negative examples and relatively few difficult positives. Explain focal loss, derive its gradient with respect to a positive example's logit, and compare it with cross entropy at probabilities 0.99, 0.5 and 0.1. Does multiplying cross entropy by a number below one always reduce the gradient magnitude? Can the resulting sigmoid score be used directly as a calibrated probability?

Original fundamentals practice, not a reported company interview. Numerical examples and derivations are original. Primary research references retrieved September 27, 2026; interview date not applicable.

1. Define confidence in the correct class

Let z be a binary logit and p = sigmoid(z) the model's score for class 1. For a hard label y, define pₜ as p when y = 1 and 1 − p when y = 0. An easy example has pₜ close to one, regardless of its class.

cross entropy: CE = −log(pₜ)
focal loss:    FL = −αₜ(1 − pₜ)^γ log(pₜ), γ ≥ 0

The class weight αₜ and the focusing parameter γ do different things. Class weights distinguish labels. The focusing factor depends on how confidently the model currently predicts each example's correct class.

All worked calculations below use αₜ = 1 for both classes. This means no class weighting. It is not the same as choosing α = 1 in the common convention that assigns α to positives and 1 − α to negatives; that convention would give negatives zero weight.

At γ = 0, the focusing factor is one and the loss becomes cross entropy, or weighted cross entropy if class weights remain. γ = 2 is an illustrative choice here, not a universal optimum.

2. Differentiate both factors

For a positive example with unit class weight, pₜ = p and dp/dz = p(1 − p). Apply the product rule:

L = −(1 − p)^γ log(p)

dL/dp = γ(1 − p)^(γ−1) log(p) − (1 − p)^γ / p

dL/dz = γp(1 − p)^γ log(p) − (1 − p)^(γ+1)

The first term comes from differentiating the focusing factor. Ignoring it changes the gradient. Cross entropy has positive-example logit gradient p − 1, so the ratio of gradient magnitudes is:

|dFL/dz| / |dCE/dz|
  = (1 − p)^(γ−1) [(1 − p) − γp log(p)]

The ratio is not merely (1 − p)^γ. That quantity scales the loss value; because it depends on the model output, its derivative also contributes to training.

For a negative example, replace p by correct-class confidence 1 − p and reverse the logit-gradient sign. Equivalently, set a signed logit s = (2y − 1)z, so pₜ = sigmoid(s), apply the positive-case formula to s and multiply by 2y − 1.

3. Compare easy, uncertain and difficult examples

For positive labels, γ = 2 and αₜ = 1:

pFocal lossFocal logit gradientCE gradientMagnitude ratio
0.990.000001005−0.000002990−0.010.000299
0.500.173287−0.298287−0.500.596574
0.101.865094−1.102019−0.901.224465

The easy example's gradient is heavily suppressed. For the difficult example at p = 0.1, the focal gradient is about 22.45% larger in magnitude than the cross-entropy gradient, even though the focal loss value is smaller than cross entropy.

At p = 0.5, explicitly evaluating the two derivative terms gives:

first term  = 2 × 0.5 × 0.5² × log(0.5) ≈ −0.173287
second term = −0.5³ = −0.125
sum         ≈ −0.298287

If the focusing factor is detached from automatic differentiation, only the second term remains. That produces −0.125 here, not −0.298287. A detached-weight training rule can be defined deliberately, but it is not the ordinary focal-loss gradient.

These values can be checked by perturbing z, recomputing p and taking a central finite difference of the scalar loss. Perturbing p instead checks dL/dp, a different derivative.

4. Check limiting behavior

For fixed γ and a nearly correct positive example, write ε = 1 − p. Since log(p) is approximately −ε:

|dL/dz| ≈ (γ + 1) ε^(γ+1)

Cross entropy has magnitude ε. Focal loss therefore suppresses very easy examples more quickly as ε approaches zero. At γ = 0 the expression reduces to the cross-entropy behavior.

For a positive example with p approaching zero and fixed γ, the logit gradient approaches −1. The loss diverges because −log(p) diverges, but the derivative through the sigmoid remains bounded in this limit. Do not infer an unbounded logit gradient from the unbounded loss.

For a fixed correct-class confidence strictly between zero and one, taking γ to infinity drives both the loss and its logit gradient toward zero. An extremely large γ can suppress useful training signal too. This is a pointwise limit, not a uniform statement about probabilities simultaneously approaching zero.

5. Account for the number of examples

Suppose a batch contains 100,000 easy negatives, each with correct-class confidence 0.99, and 100 difficult positives, each with p = 0.1. Sum absolute per-example logit gradients before any common reduction:

cross entropy:
  easy negatives: 100,000 × 0.01 = 1,000
  hard positives: 100 × 0.90 = 90

focal loss, γ = 2:
  easy negatives: 100,000 × 0.00000298997 ≈ 0.299
  hard positives: 100 × 1.102018785 ≈ 110.202

This illustrates how many individually small contributions can dominate a scalar gradient-magnitude budget, and how focal loss changes that balance. It is not the actual shared-parameter gradient: that also contains feature Jacobians, directions and cancellations. Loss reduction and parameter sharing matter.

Difficulty is not synonymous with useful information. Incorrect labels, corrupted inputs and inherently ambiguous examples may remain difficult and receive substantial attention. Inspect these slices before increasing γ. Focal loss does not identify annotation errors or guarantee minority-class recall.

6. Separate good decisions from accurate probabilities

For unweighted binary cross entropy, conditional population risk at a true positive probability η is:

R(q) = −η log(q) − (1 − η) log(1 − q)

Its minimizer is q = η. This proper-loss property concerns the ideal population problem; finite models can still be miscalibrated because of data, capacity or optimization.

For positive γ, ordinary unweighted focal loss is not strictly proper. Its ideal score need not equal the true posterior probability. The cited theoretical paper distinguishes this from classification calibration: an ideal minimizer can still induce the Bayes-optimal class decision. That term does not mean that scores of 0.8 correspond to an 80% empirical positive rate.

Neither result guarantees behavior for an imperfectly trained neural network. Class weights and changed sampling proportions also alter the training objective. Do not transfer the unweighted theorem unchanged to a weighted or resampled setting.

In practice, focal training can improve an overconfident model's empirical calibration in some settings. The theoretical lack of strict properness does not prove that every focal-trained model is worse calibrated than every cross-entropy model. It means posterior interpretation requires evidence rather than assumption.

Evaluate log loss, Brier score and reliability on a representative validation set, alongside the task's ranking and threshold metrics. If needed, fit a calibration map on separate data and evaluate it on held-out data. Cost-based thresholds should use the probability target and deployment distribution they were derived for.

7. Make implementation choices explicit

raw logits + hard labels
         ↓
stable correct-class log probability
         ↓
focusing factor × class weight × cross entropy
         ↓
explicit masking and reduction
         ↓
automatic differentiation through every factor
         ↓
task metrics + probability evaluation

Compute log probabilities stably from logits. Directly evaluating log(sigmoid(z)) can underflow for extreme negative logits. With signed logit s, log(pₜ) = −softplus(−s). For example, compute 1 − pₜ as −expm1(log(pₜ)), using an implementation with stable derivatives. This avoids directly subtracting two nearly equal floating-point numbers near one.

Keep the focusing factor connected to the gradient graph unless a different detached-weight algorithm is intended. Handle γ = 0 and masked examples explicitly. Check both labels at moderate logits with finite differences, then check finite outputs and gradients at extreme logits using the numerical precision intended for training.

Specify whether reduction is a sum, mean over all valid examples or normalization by another count such as positive examples. Different normalizers change effective gradient scale. A smaller reported training loss after changing γ or the denominator is not evidence of a better classifier.

For multilabel classification, independent sigmoid terms can be used per label with a defined masking and weighting policy. A mutually exclusive multiclass softmax problem is a different output model. Soft labels also require an explicit extension; silently substituting a fractional y into a hard-label derivation is not a complete definition.

8. Design a comparison that can answer the question

Compare ordinary cross entropy, class-weighted cross entropy and focal loss using the same data boundaries, architecture and evaluation protocol. Tune focusing and class-weight parameters on validation data, accounting for learning-rate sensitivity and loss normalization. Keep final test data out of this process.

Measure precision-recall behavior at the operating threshold, per-class performance, calibration and hard-example label quality. Where examples share users, images or time sequences, split by the relevant group to avoid near-duplicate leakage.

If the deployment class prior differs from training, reassess probability estimates and thresholds. Focal loss does not automatically undo a sampling shift. Choose it because the validated trade-off is useful, not merely because the dataset is imbalanced.

Failure analysis and self-review

  • Using p instead of pₜ for both labels: this treats confident negative predictions as difficult.
  • Multiplying the CE gradient by the loss factor: this omits the factor's derivative.
  • Increasing γ without checking noise: persistently mislabeled examples can receive disproportionate attention.
  • Reading the sigmoid score as a posterior: validate probability quality and the effects of class weighting or resampling.
  • Comparing raw training losses across γ: the objectives and scales differ.
  • Equating classification calibration with reliability: a correct class boundary is not the same as accurate probability values.

Follow-ups: What happens at γ = 0? How does detaching the focusing factor change the update? Why can a smaller loss yield a larger gradient? How would class weighting affect cost-sensitive decisions? What numerical failures arise near pₜ = 0 or 1?

A strong answer defines correct-class confidence, derives the full logit gradient and verifies the three numerical examples. An excellent answer explains aggregate contributions without mistaking them for parameter gradients, handles limiting cases and separates classification quality from probability interpretation.

Sources and attribution

Retrieved September 27, 2026. The interview framing, gradient calculations and batch example are original practice. Author affiliations do not establish an interview attribution, and none is claimed.

Continue your preparation

Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.