核密度函数的推导实现代码

library(ggplot2)
set.seed(100101)
x=sort(rnorm(1000))
k <-function(z){
  if(abs(z)<=1)
  {k=0.75*(1-z^2)}
  else
  {k=0}
  return (k)
}
f <-function(x_t,h){
  a <- c(1:1000)
  for(i in 1:1000) {
    a[i] <- k((x[i] - x_t) / h)
  }
  return((sum(a)- 3 / 4) / (999 * h))
}
L <-function(h){
  a <- c(1:1000)
  for(t in 1:1000) {
    a[t] <- log(f(x[t],h))
  }
  return(sum(a))
}
h0 <- optimize(L, c(0, 10), maximum = TRUE)
f_hat <- function(x0, h) {
  #kernel_density_estimator
  a<-c(1:1000)
  for(i in 1:1000)
  a[i] <- (k((x[i] - x0) / h))
  return(1/(1000*h)*sum(a))
}

#Step3

estimate_x <- c(1:1000)

for (i in 1:1000) {
  estimate_x[i] <- f_hat(x[i], unlist(h0)[1])
}

ggplot(data = NULL, aes(x = x, y = estimate_x)) +
  geom_point(color = "black", size = 0.1, alpha = 0.3) +
  stat_function(fun = dnorm)

画图如下
核密度函数的推导实现代码_第1张图片

你可能感兴趣的:(核密度函数的推导实现代码)