rohitg00/ai-engineering-from-scratch · error · ValueError

Cannot reshape {len(self._data)} elements into shape {shape}

Error message

Cannot reshape {len(self._data)} elements into shape {shape}

What it means

Error "Cannot reshape {len(self._data)} elements into shape {shape}" thrown in rohitg00/ai-engineering-from-scratch.

Source

Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:20

from functools import reduce
from itertools import product as iterproduct


class Tensor:
    def __init__(self, data, shape=None):
        if isinstance(data, (list, tuple)):
            self._data, self._shape = self._flatten_nested(data)
        elif isinstance(data, np.ndarray):
            self._data = data.flatten().tolist()
            self._shape = tuple(data.shape)
        else:
            self._data = [data]
            self._shape = ()

        if shape is not None:
            total = reduce(lambda a, b: a * b, shape, 1)
            if total != len(self._data):
                raise ValueError(
                    f"Cannot reshape {len(self._data)} elements into shape {shape}"
                )
            self._shape = tuple(shape)

        self._strides = self._compute_strides(self._shape)

    def _flatten_nested(self, data):
        if not isinstance(data, (list, tuple)):
            return [data], ()
        if len(data) == 0:
            return [], (0,)

        sub_results = [self._flatten_nested(item) for item in data]
        sub_shape = sub_results[0][1]
        for i, (_, s) in enumerate(sub_results):
            if s != sub_shape:
                raise ValueError(
                    f"Inconsistent shapes at index {i}: {s} vs {sub_shape}"

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:20 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/42d1051a0e18699c. Report an issue: GitHub.