Gram Matrix for Style
Implement a function to compute the Gram matrix for neural style transfer, which is a crucial component in capturing the style of an image. This task involves understanding how to represent the style of an image using feature maps extracted from a Convolutional Neural Network (CNN).
The Gram matrix is used to capture the style by computing correlations between feature maps, where the input features is a 3D array of shape , the output of a CNN layer with channels, height , and width . Each channel's grid is flattened into a vector, giving the feature map of shape . The Gram matrix is a 2D tensor that represents the correlations between these feature maps.
Here are the steps to compute the Gram matrix:
- Extract the feature map from a CNN layer.
- Compute the correlations between the feature maps. The Gram matrix can be computed using the formula , which represents the dot product of the and feature maps. The result is then normalized by the total number of elements :
Return as a array.
The style loss is then computed as the squared difference between the Gram matrix of the content image and the Gram matrix of the style image: .
This technique is widely used in image generation and editing tasks.
Example
features = CNN activations shape (64, 32, 32)
Gram matrix shape (64, 64)
featuresholds channels, each a grid of activations. Read each channel's grid as one vector of numbers; channel becomes row , so is .- Entry is the dot product of channel 's vector with channel 's: . It is large when the two channels fire at the same spatial positions.
- Every pair of the 64 channels gets one entry, so the result is , matching the output
Gram matrix shape (64, 64). The spatial size disappears entirely. - Divide by . Check with all-ones activations: each raw dot product is , and .
- Notice is symmetric () and its diagonal is channel 's energy, never negative. Shuffling pixel positions identically in all channels leaves unchanged, which is why it captures style rather than layout.
Constraints
- features: Feature maps from CNN (C, H, W)
- Return: Gram matrix (C, C)