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

Cannot multiply shapes

Error message

Cannot multiply shapes {self.shape} and {other.shape}: inner dimensions {self.cols} != {other.rows}

What it means

Raised in Matrix.matmul (reached via the @ operator) when the left matrix's column count differs from the right matrix's row count. The inner dimensions of a matrix product must agree; otherwise the dot products over rows/columns cannot be formed.

Solutions

  1. Transpose one operand if the argument order is swapped (A @ B.T)
  2. Check intermediate shapes in the pipeline to find where a dimension was dropped
  3. Insert an explicit reshape/projection so the inner dimensions match before multiplying
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/01-math-foundations/02-vectors-matrices-operations/code/matrices.py:94 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/c27c0cc104d751c4. Report an issue: GitHub.

Appendix: source

Thrown at phases/01-math-foundations/02-vectors-matrices-operations/code/matrices.py:94

            [self.data[i][j] - other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ])

    def scalar_multiply(self, scalar):
        return Matrix([
            [self.data[i][j] * scalar for j in range(self.cols)]
            for i in range(self.rows)
        ])

    def element_wise_multiply(self, other):
        return Matrix([
            [self.data[i][j] * other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ])

    def matmul(self, other):
        if self.cols != other.rows:
            raise ValueError(
                f"Cannot multiply shapes {self.shape} and {other.shape}: "
                f"inner dimensions {self.cols} != {other.rows}"
            )
        return Matrix([
            [
                sum(self.data[i][k] * other.data[k][j] for k in range(self.cols))
                for j in range(other.cols)
            ]
            for i in range(self.rows)
        ])

    def __matmul__(self, other):
        return self.matmul(other)

    def transpose(self):
        return Matrix([
            [self.data[j][i] for j in range(self.rows)]
            for i in range(self.cols)

View on GitHub (pinned to 39ea8a1c6d)