AI Wiki中文/EN

Tensor products

张量积

Derive Kronecker blocks and apply product maps without expanding them.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Act on two coordinates without building a giant matrix

Suppose a table records one feature for every pair of row and column categories. You want to transform the row categories with one matrix and the column categories with another. One route builds a large matrix acting on every pair at once. Another applies the two small matrices on opposite sides of the table. Tensor products explain why these descriptions agree.

Do not confuse this operation with elementwise multiplication, a dot product, or merely storing a higher-order array. A tensor product keeps both sets of coordinates. Later contractions may sum over selected coordinates, but forming a product does not perform that sum.

Read vector spaces, matrix multiplication and tensors and shapes first. Here every vector space is finite-dimensional over the real numbers, with a chosen basis.

A basis for pairs of coordinates

If U and V have bases e₁,…,eₘ and f₁,…,fₙ, construct U⊗V as the vector space with basis elements eᵢ⊗fⱼ. It has dimension mn. For u and v, define their product by expanding both coordinate lists:

u⊗v=∑i=1m∑j=1nuivj(ei⊗fj).u\otimes v=\sum_{i=1}^{m}\sum_{j=1}^{n}u_i v_j(e_i\otimes f_j).

This construction is linear in u with v fixed, and linear in v with u fixed: it is bilinear. A general element is a sum of such products. It need not be a single product. For example, the 2×2 identity coordinate table cannot equal uvᵀ: its two independent columns cannot both be multiples of one u.

The chosen ordering of paired indices determines how coordinates are stored. Switching factors gives a natural coordinate permutation, not generally the same ordered array. Keep that ordering visible when moving from algebra to code.

The Kronecker product is a block representation

For A of shape m×n and B of shape p×q, their Kronecker product replaces each scalar entry of A with that scalar times the whole matrix B. In zero-based indices:

(A⊗B)ip+r,jq+s=AijBrs,A⊗B∈Rmp×nq.(A\otimes B)_{ip+r,jq+s}=A_{ij}B_{rs},\qquad A\otimes B\in\mathbb R^{mp\times nq}.

This is the coordinate matrix of the product of the two linear maps in the corresponding product bases. NumPy 1.26’s kron reference describes the block construction. It does not mean A and B must be square, and it differs from their ordinary matrix product, which requires matching inner dimensions and sums over an index.

Fix the flattening convention before using vec

Let X have shape n×q. Define vec(X) to stack columns from left to right. Then:

vec⁡(AXBT)=(B⊗A)vec⁡(X),A∈Rm×n,B∈Rp×q.\operatorname{vec}(AXB^T)=(B\otimes A)\operatorname{vec}(X),\qquad A\in\mathbb R^{m\times n},\quad B\in\mathbb R^{p\times q}.

The order B⊗A follows from column stacking. To derive it, output entry (i,r) is the sum of AᵢⱼXⱼₛBᵣₛ over j and s. Under column stacking it occupies position i+mr, while Xⱼₛ occupies j+ns. The coefficient at these positions in B⊗A is exactly BᵣₛAᵢⱼ. The Matrix Cookbook, §10.2 records the column-stacking vec convention and its matrix-product identity.

This is an algebraic equality, not a command to materialize the large matrix. Storing B⊗A costs mnpq entries. Computing AX first and then multiplying by Bᵀ uses O(mnq+mqp) dense arithmetic and an m×q intermediate, in addition to the output and inputs. The alternative association A(XBᵀ) may be cheaper for other dimensions. The explicit Kronecker matrix-vector route uses O(mnpq) arithmetic and large storage.

Compare the compact action with the expanded one

Use Python 3.12 and NumPy 1.26.4. This complete program accepts nonempty integer matrices with axis lengths at most 16 and values from −10 to 10. Casting to int64 avoids small-integer arithmetic; an output sums at most 256 triple products of magnitude at most 1,000, safely inside int64. The explicit Kronecker matrix is built only to check the small example.

import numpy as np


def pair_action(a,x,b):
    values=[]
    for raw in (a,x,b):
        v=np.asarray(raw)
        if v.ndim != 2 or any(s == 0 or s > 16 for s in v.shape):
            raise ValueError('nonempty matrices with axes at most 16 required')
        if v.dtype.kind not in 'iu' or np.any(v < -10) or np.any(v > 10):
            raise ValueError('integer entries in [-10,10] required')
        values.append(v.astype(np.int64))
    a,x,b=values
    if a.shape[1] != x.shape[0] or b.shape[1] != x.shape[1]:
        raise ValueError('expected A(m,n), X(n,q), B(p,q)')
    structured=a@x@b.T
    large=np.kron(b,a)
    flattened=large@x.ravel(order='F')
    explicit=flattened.reshape(structured.shape,order='F')
    return structured,explicit,large.shape


if __name__ == '__main__':
    a=[[1,2],[-1,0]]
    x=[[1,2],[3,4]]
    b=[[1,0],[0,1],[1,-1]]
    direct,expanded,shape=pair_action(a,x,b)
    assert np.array_equal(direct,expanded)
    print('result:',direct.tolist())
    print('column vector:',direct.ravel(order='F').tolist())
    print('Kronecker shape:',shape)

Output:

result: [[7, 10, -3], [-1, -2, 1]]
column vector: [7, -1, 10, -2, -3, 1]
Kronecker shape: (6, 4)

First, AX has rows [7,10] and [−1,−2]. The three rows of B select the first column, select the second, and subtract the second from the first. This produces the displayed 2×3 answer. Column stacking interleaves its two rows in each column; NumPy therefore needs order='F' on both flattening and reconstruction.

Neither the input matrices nor the mathematics require Fortran-contiguous memory. Here order='F' specifies the index traversal. Using the default row traversal with the same Kronecker matrix can produce the wrong answer even though every dimension agrees.

Product structure must come from the problem

A general linear map on a product space need not be a single Kronecker product. Replacing it by B⊗A imposes a separable structure. Sums of Kronecker products are more expressive but cost more. Likewise, reshaping a covariance matrix does not establish statistical independence or prove that the covariance factors.

Kronecker products are useful for structured grids, separable operators and some curvature approximations. Their benefit depends on using the structure without expanding it. The program deliberately does both forms for verification; it is not a memory-efficient large-scale solver or a performance benchmark.

Coordinates depend on bases, and flattening depends on index order. Sparse factors, different contraction orders and floating-point rounding may change implementation choices. The bounded integer experiment establishes exact agreement in its domain; it makes no accuracy or speed claim for an arbitrary floating-point workload.

Follow one coefficient through the large matrix

  1. A is 2×3 and B is 4×5. What is the shape of A⊗B? Is AB defined?

Answer 1: A⊗B is 8×15. AB is not defined because A’s three columns do not match B’s four rows.

  1. With A=[[1,2],[3,4]] and B=[[0,5]], what is A⊗B?

Answer 2: Its rows are [0,5,0,10] and [0,15,0,20]. Every A entry scales one copy of the row B.

  1. Stack the columns of [[7,10,−3],[−1,−2,1]]. Why is row-major flattening different?

Answer 3: Column stacking gives [7,−1,10,−2,−3,1]. Row-major flattening gives [7,10,−3,−1,−2,1]; it uses a different pairing of positions and cannot be substituted into the same vec identity unchanged.

  1. Does the 2×2 identity coordinate table equal a single uvᵀ?

Answer 4: No. A nonzero outer product has column rank one, whereas the identity has rank two. It is the sum e₁e₁ᵀ+e₂e₂ᵀ, corresponding to a sum of two simple tensors.

Recognize structure before choosing storage

Use the Matrix Cookbook to check vec and Kronecker identities with a declared index convention, and NumPy’s reference to connect that convention to an implementation. The example and its coefficient derivation are original; the useful habit is to verify one output coordinate before trusting a compact formula.

Continue with matrix calculus: the least-squares Hessian can be expressed after vectorization, yet applied without constructing that full matrix. A practical extension is a sum of two separable operators. Implement both structured actions, add their results, and compare with the sum of two explicit Kronecker matrices on a tiny rectangular fixture.

Make a prediction, then check

For column-stacking vec, which matrix acts on vec(X) to give vec(AXBᵀ)?

Choose one answer

Learning objectives

  • Distinguish a simple tensor from a sum of products.
  • Derive the column-stacking identity and avoid materializing large products.

Prerequisites & connections

Explore related knowledge →

References

  1. The Matrix Cookbook — November 15, 2012
    Kaare Brandt Petersen; Michael Syskind Pedersen · 2012
  2. numpy.kron — NumPy 1.26
    NumPy developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.

  • Four tests passed against literal rectangular results, Kronecker blocks, column-stacking order and the maximum integer bound. Three paired formulas and four answers render.
  • Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.