How to use sample weights with tensorflow datasets?
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
Sample weights let you tell TensorFlow that some training examples should matter more than others. This is useful for class imbalance, noisy data, or any problem where one example should contribute more strongly to the loss than another.
With TensorFlow datasets, the main rule is simple: the dataset should yield (features, labels, sample_weight) triples if you want model.fit() to consume sample weights directly. Once the dataset structure matches that expectation, the rest is straightforward.
Build a Dataset That Includes Weights
A minimal example looks like this:
Each example now has a feature tensor, a label, and a sample weight. The larger weight means the model's loss calculation will pay more attention to that example.
Train a Keras Model with Weighted Samples
Keras understands that third dataset element automatically when using fit():
No separate sample_weight= argument is needed here because the dataset already provides the weights as part of each training example.
Why This Structure Matters
Keras expects one of these shapes during training:
- '
(x, y)' - '
(x, y, sample_weight)'
That means the dataset itself must yield the third component if you want weights to travel through the input pipeline cleanly. If the dataset yields only features and labels, sample weights have to be passed some other way.
Compute Weights Dynamically
Sometimes weights are derived from labels rather than stored explicitly. You can attach them with map():
This is useful when class weighting logic is simple and can be derived on the fly.
Use Sample Weights Deliberately
Sample weighting is powerful, but it changes the optimization objective. If weights are poorly chosen, training can become biased in the wrong direction.
That means you should use weights when there is a real modeling reason, not just because the API makes it possible.
Sample Weights Versus Class Weights
Class weights are attached to label classes, while sample weights belong to individual examples. If every example in a class should be treated the same way, class weights may be simpler. If individual rows need different influence, sample weights are the better fit.
This distinction matters because the data pipeline and training API handle those two weighting strategies in slightly different ways.
It is worth deciding that choice explicitly before the input pipeline grows more complex.
Common Pitfalls
- Building a dataset that yields only
(features, labels)and expecting weights to be inferred automatically. - Confusing sample weights with class weights. They are related but not identical.
- Applying very large weights without checking how they distort training.
- Forgetting that weighted losses may change metric interpretation.
- Adding weights late in the pipeline without confirming the dataset structure still matches Keras expectations.
Summary
- TensorFlow datasets can carry sample weights directly as
(x, y, sample_weight)tuples. - Keras
fit()understands that structure automatically. - Weights can be loaded explicitly or computed with
Dataset.map(). - Use sample weighting when some examples should influence loss more than others.
- Check that the dataset structure matches what the training loop expects.
Related reading
- how to use scipy.optimize.linear_sum_assignment in tensorflow or keras?
- 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 scikit-learn PCA for features reduction and know which features are discarded
- How to use SGD for time series analysis
- How to use Tensorflow addons' metrics correctly in functional API?
- How to use Tensorflow dataset API with training and validation sets
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free 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.