Skip to content

Image understanding, generation, and 3D reconstruction · Object detection · VIS006 · Model

RetinaNet with focal loss

RetinaNet combines a feature pyramid with dense detection heads and focal loss to reduce domination by easy background examples.

Partly runs in CodeSplash Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method covers part of this entry; some options or variants aren't built yet.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Partly runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through learn.cnn, learn.torch_mlp. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

RetinaNet combines a feature pyramid with dense detection heads and focal loss to reduce domination by easy background examples. This entry counts the detector and its central loss innovation together rather than duplicating them as independent models.

Question / hypotheses

Does downweighting easy dense examples improve detection under the observed foreground/background imbalance? This is a modeling/evaluation question, not a formal null-hypothesis test.

Architecture / computational structure

A backbone/FPN supplies multi-scale features to shared classification and box-regression subnetworks. Dense anchor matches provide supervision, while a modulated classification loss downweights already well-classified examples.

Assumptions

Incorrect labels or genuinely hard background examples can receive disproportionate attention. Focal loss addresses one source of imbalance; anchor coverage, long-tail classes and domain shift remain separate problems.

Formula / computational definition

FL(pt)=−αt(1−pt)γlog⁡ptFL(p_t)=-\alpha_t(1-p_t)^\gamma\log p_t, with pt=pp_t=p for a positive class and 1−p1-p otherwise. Gamma controls focusing, alpha balances classes; the full detector adds a localization loss.

Parameters and notation

Notation: Here p is a sigmoid class probability, p_t is the probability assigned to the true binary label, alpha_t the label-specific balancing weight and gamma≥0 the focusing exponent. Gamma=0 recovers alpha-weighted cross-entropy.

Learned or estimated: Backbone/FPN, classification subnet and box-regression subnet weights.

Hyperparameters and effects: Focusing gamma, class-balance alpha, anchor shapes/scales, classification initialization, loss normalization and thresholds. Increasing gamma suppresses easy-example contributions but does not guarantee better calibration or robustness.

Fitting, fine-tuning, and adaptation

Fit target class/box heads with compatible feature initialization, then fine-tune higher backbone stages at a lower rate. Tune alpha/gamma jointly with sampling and normalization on validation data, keeping the test set locked. Monitor source classes and target calibration; a classification-loss decrease is not sufficient evidence of better detection.

How to use and calibrate

Split by independent image source, scene, subject or capture sequence before augmentation; keep near-duplicate frames and crops in the same split. Report AP by class/size, loss contributions from easy versus hard negatives, calibration and inference cost. Compare focal loss with ordinary cross-entropy under matched architecture and training budget.

Example application

Detect sparse objects in images where easy background anchors greatly outnumber positives. This is a proposed use case, not a claim of validated performance on supplied real data.

Interpretation / pitfalls

Watch out

A training loss, confidence score or attention map is not a p-value or causal explanation. Confidence calibration, annotation quality and distribution-shift performance need separate assessment. A correct component calculation does not validate the full architecture, checkpoint or deployment pipeline.

Python and R code examples

Scope: The focal classification loss on correctly labeled easy and hard positive examples; no RetinaNet feature pyramid or detector fitting. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: verified RetinaNet implementations. R: native torch focal-loss/head components or a Python bridge. The example compares cross-entropy and focal weights for easy and difficult binary predictions.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — The focal classification loss on correctly labeled easy and hard positive examples; no RetinaNet feature pyramid or detector fitting. Use the shared setup.

Shared setup for this chapter
import numpy as np
from itertools import permutations
def softmax(x):
    x=np.asarray(x,dtype=float)
    e=np.exp(x-x.max(axis=-1,keepdims=True))
    return e/e.sum(axis=-1,keepdims=True)
def bilinear(a,y,x):
    y=float(np.clip(y,0,a.shape[0]-1)); x=float(np.clip(x,0,a.shape[1]-1))
    y0=int(np.floor(y)); x0=int(np.floor(x))
    y1=min(y0+1,a.shape[0]-1); x1=min(x0+1,a.shape[1]-1)
    dy=y-y0; dx=x-x0
    return (1-dy)*((1-dx)*a[y0,x0]+dx*a[y0,x1])+dy*((1-dx)*a[y1,x0]+dx*a[y1,x1])
p_t=np.array([.99,.8,.2]); alpha=.25; gamma=2.
ce=-np.log(p_t)
focal=-alpha*(1-p_t)**gamma*np.log(p_t)
ratio=focal/(alpha*ce)
assert np.allclose(ratio,(1-p_t)**2) and ratio[0]<ratio[-1]
print('CE:',ce,'focal:',focal,'relative modulation:',ratio)
R

Component demo, not a trained model — The focal classification loss on correctly labeled easy and hard positive examples; no RetinaNet feature pyramid or detector fitting. Use the shared setup.

Shared setup for this chapter
softmax <- function(x) {
  if(is.null(dim(x))) {e<-exp(x-max(x)); return(e/sum(e))}
  t(apply(x,1,function(v) {e<-exp(v-max(v)); e/sum(e)}))
}
bilinear <- function(a,y,x) {
  y<-min(max(y,0),nrow(a)-1); x<-min(max(x,0),ncol(a)-1)
  y0<-floor(y); x0<-floor(x); y1<-min(y0+1,nrow(a)-1); x1<-min(x0+1,ncol(a)-1)
  dy<-y-y0; dx<-x-x0
  (1-dy)*((1-dx)*a[y0+1,x0+1]+dx*a[y0+1,x1+1])+dy*((1-dx)*a[y1+1,x0+1]+dx*a[y1+1,x1+1])
}
p_t<-c(.99,.8,.2); alpha<-.25; gamma<-2
ce<--log(p_t); focal<--alpha*(1-p_t)^gamma*log(p_t)
ratio<-focal/(alpha*ce)
stopifnot(max(abs(ratio-(1-p_t)^2))<1e-12,ratio[1]<ratio[3])
print(list(CE=ce,focal=focal,relative_modulation=ratio))

Sources

From the CodeSplash reference, entry VIS006.