v9.1.1
Menu

Gram Matrix Computation

mediumFREENeural Style TransferStyle TransferCV: Computational Photography

Compute the Gram matrix to capture style/texture statistics.

In neural style transfer, we need a way to represent the "style" of an image independent of its content. The Gram matrix captures correlations between feature channels, representing texture patterns.

Given feature map F of shape (C, N) where C is channels and N is spatial positions:

Gij=∑k=1NFik⋅FjkG_{ij} = \sum_{k=1}^{N} F_{ik} \cdot F_{jk}

Or in matrix form: G=F⋅FTG = F \cdot F^T

The Gram matrix is:

  • Size C × C (one entry per pair of channels)
  • Symmetric (Gij=GjiG_{ij} = G_{ji})
  • Captures which features tend to activate together

High correlation between two channels means those features often co-occur, representing a texture pattern.

Example

Input
gram_matrix([[1, 2], [3, 4]])
Output
[[5, 11], [11, 25]]
Reasoning
  • features is the feature map FF, a 2×22 \times 2 grid: each row is one channel, each column one spatial position. Channel 1 holds (1,2)(1, 2) and channel 2 holds (3,4)(3, 4).
  • Each entry GijG_{ij} pairs channel ii with channel jj, multiplies values position by position, and adds the products.
  • Diagonal: G11=1⋅1+2⋅2=5G_{11} = 1 \cdot 1 + 2 \cdot 2 = 5 and G22=3⋅3+4⋅4=25G_{22} = 3 \cdot 3 + 4 \cdot 4 = 25. These are each channel's squared length (how strongly that channel fires overall).
  • Off-diagonal: G12=1⋅3+2⋅4=11G_{12} = 1 \cdot 3 + 2 \cdot 4 = 11, and G21G_{21} multiplies the same pairs in the other order, so it is also 1111.
  • The output [[5, 11], [11, 25]] is C×C=2×2C \times C = 2 \times 2, symmetric about its diagonal, and holds whole numbers because the inputs are integers and nothing is normalised.
  • Notice the size depends only on the channel count: a single channel of three 1s gives the 1×11 \times 1 result [3][3], while 3 channels at one position give a 3×33 \times 3 matrix.

Constraints

  • features: 2D list of shape [channels][spatial_positions]
  • Return: Gram matrix as 2D list of shape [channels][channels]
  • Each entry G[i][j] is the dot product of row i and row j

More from CV: Computational Photography

solution.py

Test results

Sign in to run your code against the test cases.