当R计算密度(x)时,它使用n = 512(我相信),因此它随机尝试选取512个点,并使用这些点对密度函数进行插值。我有一个要计算随机采样512点的密度(x)INSTEAD时要使用的点(p)的列表。 (忽略可能导致的任何复杂性,有效性等-我只是在寻找一种实现方法)
因此,在进行了一些研究之后,您可以按以下方式计算内核密度估计值(根据Wikipedia:]
#The same code with R language
#` Data
set.seed(1) #Used for reproducibility
data = c(rnorm(100,-10,1),rnorm(100,10,1)) #Two Normals mixed
#` True
phi = function(x) exp(-.5*x^2)/sqrt(2*pi) #Normal Density
tpdf = function(x) phi(x+10)/2+phi(x-10)/2 #True Density
#` Kernel
h = sd(data)*(4/3/length(data))^(1/5) #Bandwidth estimated by Silverman's Rule of Thumb
Kernel2 = function(x) mean(phi((x-data)/h)/h) #Kernel Density
kpdf = function(x) sapply(x,Kernel2) #Elementwise application
#` Plot
x=seq(-25,25,length=1000) #Linear Space
plot(x,tpdf(x),type="l",ylim=c(0,0.23),col="red") #Plot True Density
par(new=T)
plot(x,kpdf(x),type="l",ylim=c(0,0.23),xlab="",ylab="",axes=F) #Plot Kernel Density with Silverman's Rule of Thumb
注意,我可以根据需要选择x