Python
Machine Learning
Error Handling
Data Preprocessing
TensorFlow

ValueError Data cardinality is ambiguous. Make sure all arrays contain the same number of samples

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

This error means Keras or TensorFlow received training inputs whose first dimension does not line up. In other words, one input array says there are N samples while another says there are M samples, so the framework cannot decide which examples belong together. The fix is almost always to inspect shapes and verify that every input and target array has the same sample count along axis 0.

What "Cardinality" Means Here

In this context, cardinality does not mean feature count or tensor rank. It means how many training examples are present.

For example:

  • 'x.shape == (100, 20) means 100 samples with 20 features each'
  • 'y.shape == (80,) means 80 labels'

Those cannot be paired safely, so training fails.

A minimal example that triggers the error:

python
1import numpy as np
2import tensorflow as tf
3
4x = np.random.randn(100, 10).astype('float32')
5y = np.random.randint(0, 2, size=(80,))
6
7model = tf.keras.Sequential([
8    tf.keras.layers.Dense(1, activation='sigmoid', input_shape=(10,))
9])
10model.compile(optimizer='adam', loss='binary_crossentropy')
11
12model.fit(x, y, epochs=1)

Here x has 100 samples and y has 80, so Keras stops immediately.

The First Debug Step: Print Shapes

When this error appears, the first action should be to print the shapes of every input and output array involved.

python
print('x shape:', x.shape)
print('y shape:', y.shape)

For multi-input models, print them all:

python
print(image_input.shape)
print(text_input.shape)
print(labels.shape)

The sample dimension must agree across all of them.

Common Causes

A few patterns cause this error repeatedly.

Train-Test Splits Applied Inconsistently

If you split features and labels separately instead of in one coordinated call, they can drift apart.

Correct pattern:

python
from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

Wrong pattern:

  • split x one way
  • split y another way
  • assume they still align

Accidental Reshaping

Sometimes a preprocessing step changes a batch dimension by mistake.

python
x = x.reshape(-1, 10)

This may be correct, but if the reshape logic is wrong, it can silently change how many samples the array appears to have.

Multiple Inputs with Different Lengths

In multi-input models, all inputs must refer to the same number of examples.

python
image_input = np.random.randn(100, 32, 32, 3).astype('float32')
text_input = np.random.randn(90, 50).astype('float32')
labels = np.random.randint(0, 2, size=(100,))

This is invalid because the inputs disagree on how many training rows exist.

Fixing the Problem in Practice

A clean debugging workflow is:

  1. print all shapes
  2. identify the array with the wrong sample count
  3. trace back to the preprocessing step that created it
  4. fix the data pipeline before model training

For example, a corrected binary classification setup:

python
1import numpy as np
2import tensorflow as tf
3
4x = np.random.randn(100, 10).astype('float32')
5y = np.random.randint(0, 2, size=(100,))
6
7model = tf.keras.Sequential([
8    tf.keras.layers.Dense(1, activation='sigmoid', input_shape=(10,))
9])
10model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
11
12model.fit(x, y, epochs=1, batch_size=16)

Now both arrays describe the same 100 samples.

With tf.data.Dataset

If you use tf.data, the mismatch can come from building features and labels from different sources or different filtering rules. The same principle still applies: each example must have one corresponding target.

If the pipeline is complicated, test a small batch explicitly before training.

python
for batch_x, batch_y in dataset.take(1):
    print(batch_x.shape, batch_y.shape)

That often exposes the mismatch earlier.

Common Pitfalls

A common mistake is focusing on feature dimension mismatches when the error is actually about the number of samples.

Another mistake is slicing x and y independently and assuming they still align afterward.

People also often preprocess one input branch differently in a multi-input model and forget that sample counts still must match across branches.

Finally, if the arrays came from Pandas, verify that filtering and indexing steps did not drop rows from one object but not the other.

Summary

  • This error means the inputs and targets do not agree on how many samples exist along axis 0
  • Print every relevant shape before changing model code
  • The most common causes are inconsistent splitting, accidental reshaping, and multi-input pipelines with mismatched lengths
  • Fix the data pipeline, not the error message site inside model.fit
  • Use one coordinated split and one coordinated filtering path for features and labels
  • In Keras, every input sample must correspond to exactly one aligned target sample

Course illustration
Course illustration

All Rights Reserved.