v9.1.1
Menu

VAE Reparameterization Trick

mediumPROGenerative ModelsMachine Learning 2

Implement the reparameterization trick used in Variational Autoencoders.

The encoder outputs mean μ\mu and log-variance log⁡σ2\log\sigma^2 for each latent dimension. To sample zz in a differentiable way:

  1. Compute standard deviation: σ=elog⁡σ22\sigma = e^{\frac{\log\sigma^2}{2}}
  2. Sample: z=μ+σ⋅ϵz = \mu + \sigma \cdot \epsilon

where ϵ\epsilon is a random sample from N(0,1)\mathcal{N}(0, 1).

Given μ\mu, log⁡σ2\log\sigma^2, and pre-generated ϵ\epsilon values, compute the latent sample zz.

Return zz as a list rounded to 4 decimal places.

Example

Input
mu = [0.5, -0.3]
log_var = [0.0, 0.0]
epsilon = [1.0, -1.0]
Output
[1.5, -1.3]
Reasoning
  • Inputs: each list has one entry per latent dimension, here 2. mu holds the encoder's means μ=(0.5,−0.3)\mu = (0.5, -0.3), log_var holds log⁡σ2=(0,0)\log\sigma^2 = (0, 0), and epsilon holds noise already drawn from N(0,1)\mathcal{N}(0, 1): ϵ=(1.0,−1.0)\epsilon = (1.0, -1.0).
  • Spread: a log-variance of 00 means σ2=1\sigma^2 = 1, so σ=e0/2=e0=1\sigma = e^{0/2} = e^0 = 1 in both dimensions. The noise is passed through unscaled.
  • Shift and scale: dimension 1 gives z1=0.5+1⋅1.0=1.5z_1 = 0.5 + 1 \cdot 1.0 = 1.5; dimension 2 gives z2=−0.3+1⋅(−1.0)=−1.3z_2 = -0.3 + 1 \cdot (-1.0) = -1.3.
  • Output: [1.5, -1.3], one zz per dimension, same length as the inputs. Both values already have fewer than 4 decimal places, so rounding leaves them as is.
  • Notice: zz is a deterministic function of μ\mu and σ\sigma once ϵ\epsilon is fixed, which is why gradients can flow through it. With log⁡σ2=2\log\sigma^2 = 2 the spread becomes σ=e1≈2.7183\sigma = e^{1} \approx 2.7183, so μ=1.0\mu = 1.0, ϵ=0.5\epsilon = 0.5 gives z≈1.0+1.3591=2.3591z \approx 1.0 + 1.3591 = 2.3591.

Constraints

  • mu: 1D list of means
  • log_var: 1D list of log-variances
  • epsilon: 1D list of random normal samples (same length)
  • Return 1D list of z values rounded to 4 decimal places

Learn this in

More from Machine Learning 2

PRO

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

Sign in to run your code against the test cases.