how to use scipy.optimize.linear_sum_assignment in tensorflow or keras?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
scipy.optimize.linear_sum_assignment is useful in TensorFlow or Keras when you need an optimal one-to-one matching, but it is important to treat it as a discrete preprocessing step rather than as a differentiable model operation. The usual pattern is to compute a cost matrix in TensorFlow, run the Hungarian assignment in SciPy, and then bring the matched indices back into TensorFlow for the actual loss calculation. That design keeps the assignment logic correct without pretending the assignment itself is part of the gradient graph.
What linear_sum_assignment Does
The function solves the linear sum assignment problem, also called the Hungarian matching problem. Given a cost matrix, it chooses one row-column pairing per item so that total cost is minimized.
A simple SciPy example:
In machine learning, this appears in object detection, clustering alignment, sequence alignment, and evaluation code where predictions and labels need a one-to-one match.
The Key Constraint in TensorFlow
SciPy runs on NumPy arrays and Python control flow. TensorFlow training graphs run on tensors and differentiable ops. That mismatch leads to the central design rule:
- convert the cost matrix to NumPy
- run
linear_sum_assignment - use the matched indices to gather tensors back inside TensorFlow
That is normal. The Hungarian algorithm makes a discrete combinatorial choice, so gradients flow through the matched tensors, not through the assignment decision itself.
Example: Matching Predictions to Targets
Here is a minimal TensorFlow-friendly pattern:
The assignment is computed in SciPy, but the final loss remains a TensorFlow tensor.
Using It Inside Keras Training
If you need this inside a model training loop, custom training code is usually clearer than forcing everything into a stock loss function.
This works best when the matching dimension is small enough that .numpy() conversion is not a bottleneck.
What About tf.numpy_function?
You can wrap SciPy with tf.numpy_function or tf.py_function if you need the call inside a TensorFlow pipeline boundary:
This can make integration easier, but it does not make the operation differentiable. It also makes shape handling and debugging less transparent, so it should be a deliberate integration choice rather than a default.
Common Pitfalls
- Expecting gradients through the assignment itself. Fix: treat matching as a discrete step and backpropagate only through the matched loss.
- Calling
.numpy()inside graph-only code. Fix: use eager execution for the matching section or wrap the SciPy call withtf.numpy_function. - Forgetting the cost matrix must be two-dimensional. Fix: build one assignment problem per example if the data is batched.
- Ignoring Python round-trip overhead for large cost matrices. Fix: measure the NumPy conversion cost before using the pattern at large scale.
- Trying to force the assignment into a stock loss API when the training logic is custom. Fix: use a custom
train_stepwhen the matching logic is central to training.
Summary
- '
linear_sum_assignmentis useful in TensorFlow when you need one-to-one matching.' - Run SciPy on a NumPy cost matrix, then feed the matched indices back into TensorFlow.
- Keep the final loss differentiable even though the matching step is not.
- Prefer custom training logic when matching is part of training.
- Use
tf.numpy_functiononly when you need graph integration and understand the shape and gradient trade-offs.
Related reading
- How to use several summary collections in Tensorflow?
- How to use stop_gradient in Tensorflow
- How to use TensorBoard in a Docker container on Windows
- How to use Tensorflow addons' metrics correctly in functional API?
- How to use spot instance with amazon elastic beanstalk?
- how to use tf operations in keras models
- How to use Tensorflow dataset API with training and validation sets
- How to use tensorflow debugging tool tfdbg on tf.estimator in Tensorflow?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.