Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Created June 30, 2023 05:55
Show Gist options
  • Save vankesteren/0954bab6929bf47660029da2d650077b to your computer and use it in GitHub Desktop.
Save vankesteren/0954bab6929bf47660029da2d650077b to your computer and use it in GitHub Desktop.
Figuring out whether logspline density estimation is any good
# Figuring out whether this logspline thing is any good
library(logspline)
# mixture
d1 <- function(x) 0.6*dnorm(x) + 0.3*dlnorm(x, sdlog = 0.1) + 0.1*dnorm(x, 2)
r1 <- function(n) sample(c(rnorm(round(n*.6)), rlnorm(round(n*.3), sdlog = 0.1), rnorm(round(n*.1), 2)))
set.seed(123)
x <- r1(100)
dd <- density(x, n = 1000)
ld <- logspline(x)
curve(d1(x), from = min(x), to = max(x), n = 1000, bty = "L",
main = "Density estimation methods", y = "f(x)", ylim = c(0, 1.6))
rug(x)
lines(dd, lty = 2)
plot(ld, add=TRUE, lty = 3, n = 1000)
legend("topright", lty = c(1, 2, 3), legend = c("True density", "Kernel density", "Logspline"), bty = "n")
# chisquare
d2 <- function(x) dchisq(x, 3, 1)
r2 <- function(n) rchisq(n, 3, 1)
x <- r2(100)
dd <- density(x, n = 1000)
ld <- logspline(x)
curve(d2(x), from = -1, to = 14, n = 1000, bty = "L",
main = "Density estimation methods", y = "f(x)", ylim = c(0, 0.3))
rug(x)
lines(dd, lty = 2)
plot(ld, add=TRUE, lty = 3, n = 1000)
legend("topright", lty = c(1, 2, 3), legend = c("True density", "Kernel density", "Logspline"), bty = "n")
@vankesteren
Copy link
Author

image

The mixture is well approximated by logspline

image

It does not seem much better at chisquare

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment