Skip to main content

Hungarian Loss

⚠️ This project is archived and no longer maintained. Do not use it for real training.

The solver in this package is a greedy approximation of the Hungarian algorithm, not an exact implementation. In my tests against brute-force search on random cost matrices:

  • For 4 or more objects, roughly 7–27% of matrices produced an invalid assignment: some ground-truth objects were never matched to a prediction, so they silently contributed nothing to the loss. No error is raised.
  • It is slow and unstable at larger sizes: about 0.5 s per batch of 32 at 15 objects, a segfault at 20 objects, and no result after 2 minutes at 50 objects.
  • Only square cost matrices are supported (equal numbers of true and predicted objects).
  • The "Advanced usage" example below uses slices=, but the actual parameter is slice_sizes.

When the assignment was valid it was always optimal, so the code works for very small problems (about 3 objects), but I cannot recommend it beyond that.

Use instead: scipy.optimize.linear_sum_assignment, which is exact, fast and supports rectangular matrices. This is also what DETR uses. In TensorFlow you can call it from tf.numpy_function and compute the loss on the matched pairs; gradients flow through the matched values, which is the same as in this package.

hungarian-loss Logo

Continuous Integration Status Code style: black Python Badge Tensorflow Badge Project License

When training a model that detects multiple objects in an image, both the ground-truth y_true and predicted y_pred tensors contain sets of bounding boxes — and sets have no natural order. A naive approach that matches boxes by position (first predicted box to first true box, etc.) is unstable: the model receives inconsistent gradient signals depending on the arbitrary order boxes appear in the batch, which can prevent training from converging.

The correct approach is to find, for each sample, the optimal one-to-one assignment between the predicted boxes and the ground-truth boxes — the pairing that minimises total matching cost. This is the classic assignment problem, and the Hungarian algorithm solves it in polynomial time. This project provides a pure TensorFlow implementation of Hungarian-based loss that is fully differentiable and runs on GPU, making it suitable for end-to-end training.

Installing

Install and update using pip:

~$ pip install hungarian-loss

Note, this package does not have extra dependencies except Tensorflow 🎉.

How to use it

Both interfaces expect 3-D tensors of shape (batch_size, num_objects, num_features). For example, (32, 10, 4) represents a batch of 32 images each with up to 10 objects described by 4 bounding-box coordinates.

Simple usage — function interface

Drop hungarian_loss directly into model.compile as you would any built-in Keras loss:

from hungarian_loss import hungarian_loss

model = ...

model.compile(
    optimizer='adam',
    loss={"bbox": hungarian_loss},
    loss_weights={"bbox": 1},
)

Advanced usage — class interface

Use HungarianLoss when your model head outputs more than just bounding-box coordinates — for example, coordinates plus class scores. The slices parameter lets you specify which parts of the feature vector are used for computing the assignment cost and which loss function applies to each part:

import tensorflow as tf
from hungarian_loss import HungarianLoss, compute_euclidean_distance

loss = HungarianLoss(
    slices=[4, 10],                        # 4 bbox coords + 10 class logits
    slice_index_to_compute_assignment=0,   # use bbox coords for matching
    compute_cost_matrix_fn=compute_euclidean_distance,
    slice_losses_fn=[
        tf.keras.losses.mse,               # bbox regression loss
        tf.keras.losses.categorical_crossentropy,  # class loss
    ],
    slice_weights=[1.0, 2.0],             # relative weight of each part
)

model.compile(optimizer='adam', loss=loss)

Where to use it

Let's assume you are working on a deep learning model detecting multiple objects on an image. For simplicity of this example, let's consider, that our model intends to detect just two objects of kittens (see example below).

Use-case Example

Our model predicts 2 bounding boxes where it "thinks" kittens are located. We need to compute the difference between true and predicted bounding boxes to update model weights via back-propagation. But how to know which predicted boxes belong to which true boxes? Without the optimal assignment algorithm which consistently assigns the predicted boxes to the true boxes, we will not be able to successfully train our model.

The loss function implemented in this project can help you. Intuitively you can see that predicted BBox 1 is close to the true BBox 1 and likewise predicted BBox 2 is close to the true BBox 2. the cost of assigning these pairs would be minimal compared to any other combinations. As you can see, this is a classical assignment problem. You can solve this problem using the Hungarian Algorithm. Its Python implementation can be found here. It is also used by DERT Facebook End-to-End Object Detection with Transformers model. However, if you wish to use pure Tensor-based implementation this library is for you.

How it works

To give you more insights into this implementation we will review a hypothetical example. Let define true-bounding boxes for objects T1 and T2:

Object Bounding boxes
T1 1., 2., 3., 4.
T2 5., 6., 7., 8.

Do the same for the predicted boxes P1 and P2:

Object Bounding boxes
P1 1., 1., 1., 1.
P2 2., 2., 2., 2.

Let's compute the Euclidean distances between all combinations of True and Predicted bounding boxes:

P1 P2
T1 3.7416575 2.449489
T2 11.224972 9.273619

This algorithm will compute the assignment mask first:

P1 P2
T1 1 0
T2 0 1

And then compute the final error:

loss = (3.7416575 + 9.273619) / 2 = 6.50763825

In contrast, if we would use the different assignment:

loss = (2.449489 + 11.224972) / 2 = 6.8372305

As you can see the error for the optimal assignment is smaller compared to the other solution(s).

When to use it (and when not to)

✅ Optimal matching. The Hungarian algorithm finds the assignment that minimizes total matching cost, giving the model a stable and consistent training signal regardless of the order boxes appear in the batch.

✅ Fully differentiable. Implemented in pure TensorFlow, so gradients flow through the assignment step and the model can be trained end-to-end on GPU without any NumPy or SciPy dependency.

✅ Flexible. The HungarianLoss class supports mixed outputs (e.g. bounding boxes + class scores) with per-slice loss functions and weights, making it easy to adapt to different model heads.

❌ Quadratic cost. The Hungarian algorithm runs in O(n³) time with respect to the number of objects. For a small fixed number of slots (≤ ~20) this is negligible, but for very large prediction sets it can become a training bottleneck.

❌ Fixed set size. Both y_true and y_pred must have the same number of object slots per sample. Models that predict a variable number of objects need to pad to a maximum, which adds implementation overhead.

❌ Harder to debug. The assignment step is opaque — if the loss behaves unexpectedly, inspecting which predicted boxes were matched to which ground-truth boxes requires extra instrumentation.

Contributing

For information on how to set up a development environment and how to make a contribution to Hungarian Loss, see the contributing guidelines.

Metadata

Release files for hungarian-loss 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hungarian-loss 1.0.3
File Size Uploaded Provenance Actions
hungarian_loss-1.0.3.tar.gz 307.0 kB Without provenance Details for hungarian_loss-1.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hungarian-loss 1.0.3
File Interpreter ABI Platform Actions
hungarian_loss-1.0.3-py3-none-any.whl Python 3 none any Details for hungarian_loss-1.0.3-py3-none-any.whl

Total release size: 320.6 kB

Release files / hungarian_loss-1.0.3.tar.gz

Download URL hungarian_loss-1.0.3.tar.gz
Size 307.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c47fa5c9817236a568b2c37c4b414e9ed5878946f503ec757ffb91ca7afa2e8e
BLAKE2b-256 checksum
How to use checksums
627c49704a62c488acdab9cb10e65b9288110bb60cbb43a17a92723850d7a6fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / hungarian_loss-1.0.3-py3-none-any.whl

Download URL hungarian_loss-1.0.3-py3-none-any.whl
Size 13.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bf66dbfdbe56e7cfe63c45ae9a90db3a63c6ca23e6332d1af7cf6512ab10180a
BLAKE2b-256 checksum
How to use checksums
876d929c4dd44963278e8259b242574d1f108e63af6be2f52ec2e49c7e1c36cd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for hungarian-loss 1.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page