PIXELBANKv9.1.0
Menu

Compute the style loss between generated and target Gram matrices.

Style loss measures how different the texture statistics are between the generated image and the style target. It's computed as the mean squared error between their Gram matrices:

Lstyle=1C2∑i,j(Gijgen−Gijstyle)2L_{style} = \frac{1}{C^2} \sum_{i,j} (G_{ij}^{gen} - G_{ij}^{style})^2

where:

  • GgenG^{gen} is the Gram matrix of the generated image
  • GstyleG^{style} is the Gram matrix of the style image
  • CC is the number of channels

A lower style loss means the generated image has similar texture patterns to the style reference.

Note: In practice, this is normalized by 4N2C24N^2C^2 where N is spatial size, but we use simplified MSE here.

Example:

Input:
style_loss([[1, 2], [2, 4]], [[1, 2], [2, 4]])
Output:
0.0
Reasoning:

Comparing identical Gram matrices: Difference matrix: [[0, 0], [0, 0]] Squared differences: all zeros Sum: 0 MSE: 0 / 4 = 0.0

  • When Gram matrices match exactly, style loss is zero.

Constraints:

  • G_generated and G_style: square matrices (same dimensions)
  • Return loss value rounded to 4 decimal places
  • Loss should be 0 when matrices are identical
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Style Loss Computation - Medium | PixelBank