Create your own
Lesson illustration

Dot and Matrix Products: Computing and Checking Dimensions

Welcome back. Previously, you learned to read tensor shapes as contracts: a vector of shape (d,), a matrix of shape (m, n), and speech features often organized as (batch, frames, features).

This lesson turns those contracts into computations. You will learn to calculate dot products, matrix-vector products, and matrix-matrix products, while predicting their output shapes before doing any arithmetic. That habit is essential when connecting feature extractors, neural layers, and decoders in speech systems.


Dot products: combining two equal-length vectors

A dot product takes two vectors of the same length and produces one scalar. If

and

then their dot product is

In plain language:

  1. Multiply corresponding entries.
  2. Add all of those products.
  3. The result is one number.

For example,

Both vectors have length three, so the dot product is valid:

The output has shape (): it is a scalar.

A dot product is often a weighted score. The entries of are inputs or features; the entries of state how each feature contributes to the score. Positive weights increase it, negative weights decrease it, and larger magnitudes matter more.

Vector dot product and vector length | Vectors and spaces | Linear Algebra | Khan Academy

Watch “Vector dot product and vector length” by Khan Academy for a compact visual explanation of the operation and its scalar output.

Watch the definition to see the component-by-component formula and why the result is a scalar. Then watch the examples; pause briefly before each result and check that you can pair corresponding components correctly.

Compatibility rule for dot products

The dot product requires vectors with the same number of components:

For example:

First vectorSecond vectorValid?Output
(80,)(80,)Yesscalar ()
(3,)(4,)Noundefined
(160,)(160,)Yesscalar ()

This rule is not a superficial programming constraint. If one vector has 80 log-mel features and the other has 64 learned weights, there is no meaningful way to pair every input feature with exactly one weight.

In NumPy, use @ for the linear-algebra operation:

import numpy as np

x = np.array([0.2, -0.1, 0.4])
w = np.array([1.5, 2.0, -0.5])

score = x @ w

print(score)        # -0.1
print(score.shape)  # ()

You can also write np.dot(x, w) for two vectors. Prefer @ as a default in machine-learning code: it clearly signals that you intend a linear-algebra product.

Do not confuse this with elementwise multiplication:

print(x * w)  # [ 0.3 -0.2 -0.2], shape (3,)
print(x @ w)  # -0.1, shape ()

x * w keeps one value per feature. x @ w combines the features into one score.


Matrix-vector products: one score per matrix row

A matrix-vector product generalizes the dot product. Let

and

Then

The crucial compatibility condition is that the number of columns in equals the number of entries in :

is valid, and the output has entries.

Consider

The product is valid because the inner dimensions both equal three. Each output entry is the dot product of one row of with :

There are two rows in , so the result has two entries.

In NumPy, the corresponding shapes are:

A = np.array([
    [1, -1, 2],
    [0, -3, 1],
])

x = np.array([2, 1, 0])

y = A @ x

print(A.shape)  # (2, 3)
print(x.shape)  # (3,)
print(y.shape)  # (2,)
print(y)        # [ 1 -3]

Mathematics conventionally treats as a column vector. NumPy represents it as a one-axis array with shape (3,), but the compatibility reasoning is the same: the vector must supply one value for every column of the matrix.

In a speech model, a single frame might contain acoustic features:

A learned weight matrix could contain feature detectors:

Then

Each row of computes a different weighted score from the same input frame. Later, neural-network layers will add a bias and a nonlinear activation, but this matrix-vector product is the core computation.


Matrix products: rows meet columns

Matrix multiplication uses the same idea repeatedly. If

and

then the product is defined and has shape

The shape rule is:

The two matching values are the inner dimensions. They must match. The remaining and values are the outer dimensions, and they determine the shape of the output.

A matrix with shape \(2 \times 4\) multiplies a matrix with shape \(4 \times 3\). Their matching inner size is four, so the product is valid and has shape \(2 \times 3\).

A useful memory rule is:

Inner dimensions must agree; outer dimensions remain.

For every position in the product matrix, take:

  • row of the first matrix;
  • column of the second matrix;
  • their dot product.

Formally, if

then

The index ranges over the shared inner dimension.

Multiplying a matrix by a matrix | Matrices | Precalculus | Khan Academy

Watch “Multiplying a matrix by a matrix” by Khan Academy to reinforce the shape rule and see every output entry built from a row-column dot product.

Begin with the compatibility check, focusing on why a 2 \times 3 matrix can multiply a 3 \times 2 matrix. Continue with each entry, where rows from the left matrix meet columns from the right matrix. Finish with the final matrix to verify how the four dot products become a 2 \times 2 result.

A complete matrix-product calculation

Let

and

The product is valid because the shared inner dimension is three. Its output shape must be

Compute each entry:

Notice the structure:

  • The first row of the output came from the first row of .
  • The second column of the output came from the second column of .
  • Every output entry required a dot product of length three.

In NumPy:

A = np.array([
    [1, 2, 0],
    [0, 1, 3],
])

B = np.array([
    [1.0, -1.0],
    [0.5, 2.0],
    [2.0, 0.0],
])

C = A @ B

print(C.shape)  # (2, 2)
print(C)
# [[2.  3. ]
#  [6.5 2. ]]

Shape checking before computation

Do the shape check before calculating a single entry. This prevents most multiplication mistakes.

For a proposed product :

  1. Write the shape of : .
  2. Write the shape of : .
  3. Compare and , the inner dimensions.
  4. If they match, the result has shape .
  5. If they do not match, matrix multiplication is undefined.

For example:

Proposed productCompatible?Output shape
(2, 3) @ (3, 5)Yes(2, 5)
(4, 80) @ (80, 256)Yes(4, 256)
(2, 3) @ (4, 2)Nonone
(12, 64) @ (64, 128)Yes(12, 128)

The total number of elements does not determine compatibility. A matrix of shape (2, 6) and one of shape (3, 4) both contain 12 values, but

is invalid because six does not equal three.

You can make shape validation explicit in code:

def matrix_product_checked(a, b):
    if a.ndim != 2 or b.ndim != 2:
        raise ValueError("Expected two matrices.")

    m, n = a.shape
    r, p = b.shape

    if n != r:
        raise ValueError(
            f"Incompatible shapes: {a.shape} and {b.shape}. "
            f"Expected {n} columns in the first matrix "
            f"to equal {r} rows in the second matrix."
        )

    return a @ b

This is a simplified version of a useful engineering habit: validate a tensor contract at boundaries, rather than waiting for a distant failure or silently incorrect output.


Order matters

Ordinary number multiplication is commutative:

Matrix multiplication generally is not commutative:

Sometimes reversing the order is invalid. For example, if

and

then

is valid, but

is not valid because the inner dimensions would be four and two.

Even when both orders are valid, the outputs may have different shapes and values. If has shape (2, 3) and has shape (3, 2), then:

while

They cannot be equal because they do not even have the same shape.


Why this appears constantly in speech ML

Suppose one utterance has been converted into a frame-level feature matrix:

where is the number of frames and is the number of features per frame. A typical early speech representation might have features per frame.

A learned projection matrix can have shape

where is a model’s internal representation width. The product is

The number of time frames remains unchanged; every frame has been transformed from input features into learned features.

For example:

This one shape calculation tells you several important things:

  • Each of the 200 frames supplies 80 feature values.
  • The learned matrix expects exactly 80 input features.
  • The output preserves the 200-frame time structure.
  • Each frame now has 256 learned values.

If a feature extractor produces (frames, 80) but a layer has weights shaped (64, 256), the product is invalid. That failure reflects a real interface mismatch: the model expects 64 features but receives 80.

For a batch of speech examples, libraries extend the same principle across an additional batch axis. The core operation remains unchanged: the feature width must match the appropriate weight dimension.


Key takeaways and next step

  • A dot product takes two equal-length vectors and produces one scalar.
  • A matrix-vector product has the form
  • A matrix product has the form
  • Each output element in a matrix product is a dot product between one row of the left matrix and one column of the right matrix.
  • The inner dimensions must match; the outer dimensions determine the output shape.
  • In NumPy, use @ for matrix and vector products. Do not confuse it with *, which performs elementwise multiplication.
  • Matrix order matters: and can differ in validity, shape, and values.

Next, we will move from computing values to understanding how values change: derivatives, partial derivatives, and gradients.

Can't find a good explanation? Sign up and we'll make it for you

Sign up