VAE Loss: Reconstruction plus KL

~10 mincode completion

Implement vae_loss(x, x_hat, mu, var, beta) returning a scalar.

Examples

Perfect recon and standard-normal latent: 0

Input
vae_loss([[1, 0], [0, 1]], [[1, 0], [0, 1]], [0, 0], [1, 1], 2)
Output
0

MSE 0.5, KL 0, beta ignored

Input
vae_loss([1, 2], [1, 1], [0, 0], [1, 1], 1)
Output
0.5

Recon 1, KL 0.5, beta=2 gives 2

Input
vae_loss([1], [0], [1], [1], 2)
Output
2

Hints

Hint 1

is the natural log, which is what this formula wants.

Hint 2

Make sure you are not returning negative elbo with the wrong sign.

Requirements

  • beta: KL weight

  • Return scalar

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

4 autonomy companies, 1 enterprise vendor, 1 defense company, 1 health and bio company, 1 AI product company. Top match scores 87.

Python
import numpy as np


def vae_loss(x, x_hat, mu, var, beta):
    """
    Mean reconstruction plus beta * KL to N(0, I).

    Args:
        x, x_hat: arrays of the same shape
        mu, var:  encoder Gaussian parameters
        beta:     KL weight

    Returns:
        scalar
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.