Tensorflow 2.2.0 error Predictions must be 0 Condition x y did not hold element-wise while using Bidirectional LSTM layer
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
The error "Predictions must be >= 0" or "Condition x >= y did not hold element-wise" in TensorFlow 2.2.0 occurs when the loss function receives prediction values outside the expected range. This typically happens when using binary_crossentropy or categorical_crossentropy with an output activation that does not constrain values to [0, 1]. The fix is to match the output layer's activation function with the loss function: use sigmoid for binary classification and softmax for multi-class classification.
The Error
The Dense(1) layer with no activation outputs unbounded values (negative to positive infinity). binary_crossentropy expects probabilities between 0 and 1.
Fix 1: Add the Correct Activation Function
Binary Classification
Multi-Class Classification
Fix 2: Use from_logits=True
Instead of adding an activation, tell the loss function to handle raw logits:
Using from_logits=True is numerically more stable because it combines the sigmoid/softmax with the loss computation in a single operation, avoiding log(0) issues.
Fix 3: Check Label Encoding
Activation and Loss Function Matching Table
| Task | Output Activation | Loss Function | Label Format |
| Binary classification | sigmoid | binary_crossentropy | 0 or 1 |
| Binary (from logits) | None | BinaryCrossentropy(from_logits=True) | 0 or 1 |
| Multi-class | softmax | categorical_crossentropy | One-hot |
| Multi-class (sparse) | softmax | sparse_categorical_crossentropy | Integer |
| Multi-class (logits) | None | CategoricalCrossentropy(from_logits=True) | One-hot |
| Regression | None or linear | mse | Continuous |
Complete Working Example
Common Pitfalls
- Missing activation on the output layer: The most common cause.
Dense(1)withoutactivation='sigmoid'outputs unbounded values. Bothbinary_crossentropyandcategorical_crossentropyexpect inputs in [0, 1] unlessfrom_logits=Trueis set. - Using softmax with binary_crossentropy: For binary classification,
softmaxon a single output neuron always outputs 1.0 (softmax of a single value is always 1). Usesigmoidfor binary classification or use two output neurons withsoftmaxandcategorical_crossentropy. - Labels outside the expected range: If labels contain values other than 0/1 for binary classification (e.g., -1/1 or continuous values), the loss computation fails. Verify label ranges with
y_train.min()andy_train.max()before training. - NaN in input data causing NaN predictions:
NaNvalues in the input or embedding lookup produceNaNpredictions, which violate the >= 0 condition. Check for NaN withnp.isnan(x_train).any()and clean the data before training. - Mixing up sparse and non-sparse categorical crossentropy:
categorical_crossentropyexpects one-hot encoded labels[0, 1, 0].sparse_categorical_crossentropyexpects integer labels1. Using the wrong one causes shape mismatches or out-of-range errors.
Summary
- The error occurs when predictions fall outside the range expected by the loss function
- Match activation to loss:
sigmoid+binary_crossentropy,softmax+categorical_crossentropy - Use
from_logits=Truein the loss function to accept raw logits without an activation layer - Verify label encoding: binary labels should be 0/1, multi-class should be one-hot or integer indices
from_logits=Trueis numerically more stable and preferred in modern TensorFlow code
Related reading
- Tensorflow 2.4.1 - Couldn't invoke ptxas.exe
- Tensorflow after 1.15 - No need to install tensorflow-gpu package
- Tensorflow aggregation_method for optimizers
- Tensorflow allocating GPU memory when using tf.device'/cpu0
- TensorFlow 2 custom loss No gradients provided for any variable error
- Tensorflow 2 throwing ValueError as_list is not defined on an unknown TensorShape
- Tensorflow __new__ got an unexpected keyword argument 'serialized_options' in Object Detection API
- Tensorflow access trained variables after closing the session
.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.