Skip to main content

TensorFlow implementation of focal loss.

Project description

Python Version PyPI Package Version Last Commit Travis CI Build Status GitHub Actions Build Status Code Coverage Documentation Status License

TensorFlow implementation of focal loss [1]: a loss function generalizing binary cross-entropy loss that penalizes hard-to-classify examples.

The focal_loss package provides a function binary_focal_loss and a class BinaryFocalLoss that can be used as stand-in replacements for tf.keras.losses functions and classes, respectively.

# Typical tf.keras API usage
import tensorflow as tf
from focal_loss import BinaryFocalLoss

model = tf.keras.Model(...)
    loss=BinaryFocalLoss(gamma=2),  # Used here like a tf.keras loss
history =

Documentation is available at Read the Docs.

Focal loss plot


  1. Make sure that a CPU or GPU version of TensorFlow 2.0 or later is installed (see this link for installation instructions).

  2. The focal_loss package can be installed using the pip utility. For the latest version, install directly from the package’s GitHub page:

    pip install git+

    Alternatively, install a recent release from the Python Package Index (PyPI):

    pip install focal-loss

    Note. To install the project for development (e.g., to make changes to the source code), clone the project repository from GitHub and run make dev:

    git clone
    cd focal-loss
    # Optional but recommended: create a new Python virtual environment first
    make dev

    This will additionally install the requirements needed to run tests, check code coverage, and produce documentation.


[1]T. Lin, P. Goyal, R. Girshick, K. He and P. Dollár. Focal loss for dense object detection. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2018. (DOI) (arXiv preprint)

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for focal-loss, version 0.0.2
Filename, size File type Python version Upload date Hashes
Filename, size focal_loss-0.0.2-py3-none-any.whl (15.7 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size focal-loss-0.0.2.tar.gz (12.5 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page