Skip to main content

TensorFlow implementation of focal loss.

Project description

Python Version PyPI Package Version Last Commit Build Status Code Coverage Documentation Status License

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

The focal_loss package provides functions and classes that can be used as off-the-shelf 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 =

The focal_loss package includes the functions

  • binary_focal_loss

  • sparse_categorical_focal_loss

and wrapper classes

  • BinaryFocalLoss (use like tf.keras.losses.BinaryCrossentropy)

  • SparseCategoricalFocalLoss (use like tf.keras.losses.SparseCategoricalCrossentropy)

Documentation is available at Read the Docs.

Focal loss plot


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 and activate a new environment first
make dev

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


Project details

Download files

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

Source Distribution

focal-loss-0.0.7.tar.gz (14.4 kB view hashes)

Uploaded Source

Built Distribution

focal_loss-0.0.7-py3-none-any.whl (19.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page