keras-team/keras · error · ValueError

`x` (images tensor) and `sample_weight` should have the same

Error message

`x` (images tensor) and `sample_weight` should have the same length. Found: x.shape = {np.asarray(x).shape}, sample_weight.shape = {np.asarray(sample_weight).shape}

What it means

NumpyArrayIterator (ImageDataGenerator.flow) validates that x and sample_weight have matching first dimensions. sample_weight must be None or have exactly len(x) entries, one weight per image. The error shows both shapes so you can see the mismatch.

Source

Thrown at keras/src/legacy/preprocessing/image.py:573

                if len(x) != len(xx):
                    raise ValueError(
                        "All of the arrays in `x` "
                        "should have the same length. "
                        "Found a pair with: "
                        f"len(x[0]) = {len(x)}, len(x[?]) = {len(xx)}"
                    )
        else:
            x_misc = []

        if y is not None and len(x) != len(y):
            raise ValueError(
                "`x` (images tensor) and `y` (labels) "
                "should have the same length. "
                f"Found: x.shape = {np.asarray(x).shape}, "
                f"y.shape = {np.asarray(y).shape}"
            )
        if sample_weight is not None and len(x) != len(sample_weight):
            raise ValueError(
                "`x` (images tensor) and `sample_weight` "
                "should have the same length. "
                f"Found: x.shape = {np.asarray(x).shape}, "
                f"sample_weight.shape = {np.asarray(sample_weight).shape}"
            )
        if subset is not None:
            if subset not in {"training", "validation"}:
                raise ValueError(
                    f"Invalid subset name: {subset}"
                    '; expected "training" or "validation".'
                )
            split_idx = int(len(x) * image_data_generator._validation_split)

            if (
                y is not None
                and not ignore_class_split
                and not np.array_equal(
                    np.unique(y[:split_idx]), np.unique(y[split_idx:])

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Set sample_weight to an array of length x.shape[0]
  2. If you meant class balancing, use model.fit(..., class_weight=...) instead of sample_weight in flow()
  3. Recompute/align weights after any train/validation split of x

Example fix

// before
sw = class_weights  # dict-like / len != n_samples
it = gen.flow(x, y, sample_weight=sw)
// after
model.fit(it, class_weight=class_weights)
# or: sw = np.ones(len(x))
Defensive patterns

Strategy: validation

Validate before calling

assert sample_weight is None or len(sample_weight) == len(x), (len(x), len(sample_weight))

Try / catch

try: gen.flow(x, y, sample_weight=sw)
except ValueError as e: assert 'sample_weight' in str(e); ...

Prevention

When it happens

Trigger: Calling image_data_generator.flow(x, y, sample_weight=w) where w is not None and len(w) != len(x), e.g. weights computed per-class or per-batch instead of per-sample.

Common situations: Passing class weights (from compute_class_weight) as sample_weight; slicing x after building weights; forgetting weights apply per image, not per label class.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/55e54053693d6c54. Report an issue: GitHub.