ML Foundations

Choose inner or outer products for NumPy vectors

Check the output shape of one-dimensional matrix multiplication and construct an outer product deliberately.

Example results for Choose inner or outer products for NumPy vectors. vector shapes: (3,) (3,)
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

A one-dimensional vector is not a row matrix

A NumPy array with shape (3,) is one-dimensional. Applying the matrix multiplication operator to two one-dimensional vectors produces their scalar inner product, not a three-by-three table of all pairwise products. [1]

The distinction matters when a later calculation expects a matrix. Choose the intended result and inspect its shape, rather than inferring a row or column dimension from the way a vector prints. [1, 2]

References: [1], [2]

Compare the two outputs

Run python examples/numpy_matmul_vector_shapes.py. The vectors are 1, 2, 3 and 10, 20, 30. Their inner product is 140, with scalar shape (). NumPy outer instead produces a three-by-three array of pairwise products. [1, 2]

The example inserts singleton dimensions to form an explicit column and row. Their matrix product agrees with the outer result for this fixture. Assertions check the inner value and outer shape. [1, 2]

Executed with Python 3.12.14; stdout and checksum recorded in private evidence.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
inner = a @ b
outer = np.outer(a, b)
column = a[:, None]
row = b[None, :]
print('vector shapes:', a.shape, b.shape)
print('inner:', int(inner), 'shape:', np.shape(inner))
print('outer:', outer.tolist(), 'shape:', outer.shape)
print('column by row matches:', bool(np.array_equal(column @ row, outer)))
assert inner == 140
assert outer.shape == (3, 3)

Recorded output

vector shapes: (3,) (3,)
inner: 140 shape: ()
outer: [[10, 20, 30], [20, 40, 60], [30, 60, 90]] shape: (3, 3)
column by row matches: True

References: [1], [2]

Define dimensional meaning

NumPy matmul treats a one-dimensional input specially by temporarily adding and then removing a dimension. For higher-dimensional stacks, it follows additional broadcasting rules. Check the documented shape contract for the arrays being used. [1]

The example uses real one-dimensional integer vectors. It does not cover complex conjugation, batched vectors, overflow or performance. NumPy outer flattens its inputs, so do not assume it preserves arbitrary batch dimensions. [1, 2]

References: [1], [2]

Sources

  1. NumPy matmul
  2. NumPy outer