Matrices and tensor shapes
A matrix is a rectangular grid of numbers. Its shape describes the number of rows and columns. Two rows with three entries each have shape (2, 3). In AI software, a tensor is commonly a numerical array with a specified shape and any number of axes; a vector has one axis, a matrix two, and a batch of images may have four. Mathematical tensors have additional transformation structure, which is outside this introductory lesson.
Read shapes and indices
Consider two fictional catalog items with features ordered science, history, and art. The matrix [[2, 3, 1], [1, 0, 4]] has two samples and three features. rows[1][2] selects the second row and third column, giving 4. A scalar array has shape (), a three-entry vector has shape (3,), and a column matrix with three rows has shape (3, 1). These are different shapes even though they can store the same three values. For a grayscale image batch with 8 images, 28 rows, 28 columns and 1 channel, a channels-last layout has shape (8, 28, 28, 1). Some libraries use channels first; check the axis contract. Nested Python lists need not be rectangular, so shape must be validated.
Transpose rows and columns
def transpose(rows): if not rows or not rows[0]: raise ValueError("Use a nonempty matrix") width = len(rows[0]) if any(len(row) != width for row in rows): raise ValueError("Use rectangular rows") result = [] for j in range(width): column = [] for row in rows: column.append(row[j]) result.append(column) return result
rows = [[2, 3, 1], [1, 0, 4]]print(rows[1][2])print(transpose(rows))Transposition swaps axes: (2, 3) becomes (3, 2). Each original column becomes a new row. The generator expression in any(...) checks whether at least one row length differs. This implementation returns new lists without altering the input. Transposing does not learn new features or change the numbers themselves.
Matrix multiplication combines rows with columns
A matrix with shape (m, n) can multiply a matrix with shape (n, p). The two inner dimensions must agree; the output has shape (m, p). Each output cell is the dot product of one left row and one right column. For our two sample rows, use weights [[4], [1], [2]] of shape (3, 1). The first score is 2×4 + 3×1 + 1×2 = 13; the second is 1×4 + 0×1 + 4×2 = 12. This gives a (2, 1) matrix of scores.
def shape(rows): if not rows or not rows[0]: raise ValueError("Use a nonempty matrix") width = len(rows[0]) if any(len(row) != width for row in rows): raise ValueError("Use rectangular rows") return len(rows), width
def matmul(a, b): m, n = shape(a) r, p = shape(b) if n != r: raise ValueError("Inner dimensions must agree") result = [] for i in range(m): row = [] for j in range(p): total = 0 for k in range(n): total += a[i][k] * b[k][j] row.append(total) result.append(row) return result
samples = [[2, 3, 1], [1, 0, 4]]weights = [[4], [1], [2]]scores = matmul(samples, weights)print(scores)print(shape(scores))The outer loops select an output row and column; the inner loop sums products along the shared axis. The result is a matrix even when it has one column. The simple implementation supports nonempty rectangular lists of small integers only, not sparse arrays, arbitrary tensors or accelerator execution.
Elementwise operations and broadcasting
Elementwise multiplication of equally shaped arrays multiplies corresponding cells; matrix multiplication sums products across an inner dimension. NumPy also defines broadcasting: it compares dimensions from the right, allowing equal dimensions or a dimension of size one, with missing leading dimensions treated as one. For example, (2, 3) plus (3,) gives (2, 3) by adding the same feature offset vector to each row; (2, 3) plus (2,) is incompatible. This is a conceptual library example, not executable Python list syntax. NumPy @ performs matrix multiplication for two-dimensional arrays; * is elementwise. Batched products and vector special cases have additional rules.
Practice and diagnose shape errors
Predict the output shape of (4, 3) times (3, 2) (answer: (4, 2)). Explain why (4, 3) times (2, 3) is not valid (3 differs from 2). Transposing the right matrix makes the dimensions agree, but changes the operation: do so only when the feature axes really correspond. A correct shape is not evidence that feature semantics are correct. Next, compare vectors by length and direction.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Matrices and tensor shapes — understanding check
Apply introductory linear algebra to small original fixtures.
What is the shape of [[2,3,1],[1,0,4]]?
What is the output shape of a matrix product (2, 3) @ (3, 1)?
Which ordered pair of matrix shapes is incompatible for matrix multiplication?
What is the transpose of [[1,2,3],[4,5,6]]?
Which vector shape broadcasts with (2,3) for NumPy addition?