Skip to content

Instantly share code, notes, and snippets.

@turgeonmaxime
Created July 17, 2018 03:04
Show Gist options
  • Save turgeonmaxime/86f875a614ca81138ba9d61710e969c6 to your computer and use it in GitHub Desktop.
Save turgeonmaxime/86f875a614ca81138ba9d61710e969c6 to your computer and use it in GitHub Desktop.
# This is a short script that shows how to compute the KL divergence using the kernel density estimator
# The key point is to use linear interpolation to evaluate the density at the same points
# 1. Generate a sample of standard normal variates
x <- rnorm(100)
# 2. Compute kernel density estimator
dens_obs <- density(x)
# 3. Use linear interpolation to evaluate over a grid
grid <- seq(-2, 2, length.out = 100)
dens_obs_linInt <- approxfun(dens_obs)(grid)
# 4. Compute KL divergence using flexmix package
mat <- cbind(obs = dens_obs_linInt,
theo = dnorm(grid))
flexmix::KLdiv(mat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment