【发布时间】:2015-09-04 19:56:57
【问题描述】:
我正在尝试实现内核密度估计。但是,我的代码没有提供应有的答案。它也是用 julia 编写的,但代码应该是不言自明的。
算法如下:
在哪里
因此,该算法测试 x 与由某个常数因子(binwidth)加权的观测值 X_i 之间的距离是否小于 1。如果是这样,它会将 0.5 / (n * h) 分配给该值,其中 n = #of 观察值。
这是我的实现:
#Kernel density function.
#Purpose: estimate the probability density function (pdf)
#of given observations
#@param data: observations for which the pdf should be estimated
#@return: returns an array with the estimated densities
function kernelDensity(data)
|
| #Uniform kernel function.
| #@param x: Current x value
| #@param X_i: x value of observation i
| #@param width: binwidth
| #@return: Returns 1 if the absolute distance from
| #x(current) to x(observation) weighted by the binwidth
| #is less then 1. Else it returns 0.
|
| function uniformKernel(x, observation, width)
| | u = ( x - observation ) / width
| | abs ( u ) <= 1 ? 1 : 0
| end
|
| #number of observations in the data set
| n = length(data)
|
| #binwidth (set arbitraily to 0.1
| h = 0.1
|
| #vector that stored the pdf
| res = zeros( Real, n )
|
| #counter variable for the loop
| counter = 0
|
| #lower and upper limit of the x axis
| start = floor(minimum(data))
| stop = ceil (maximum(data))
|
| #main loop
| #@linspace: divides the space from start to stop in n
| #equally spaced intervalls
| for x in linspace(start, stop, n)
| | counter += 1
| | for observation in data
| | |
| | | #count all observations for which the kernel
| | | #returns 1 and mult by 0.5 because the
| | | #kernel computed the absolute difference which can be
| | | #either positive or negative
| | | res[counter] += 0.5 * uniformKernel(x, observation, h)
| | end
| | #devide by n times h
| | res[counter] /= n * h
| end
| #return results
| res
end
#run function
#@rand: generates 10 uniform random numbers between 0 and 1
kernelDensity(rand(10))
这是被退回的:
> 0.0
> 1.5
> 2.5
> 1.0
> 1.5
> 1.0
> 0.0
> 0.5
> 0.5
> 0.0
其和为:8.5(累积分布函数,应为1。)
所以有两个bug:
- 值未正确缩放。每个数字应约为其当前值的十分之一。事实上,如果观察次数增加 10^n n = 1, 2, ... 那么 cdf 也会增加 10^n
例如:
> kernelDensity(rand(1000))
> 953.53
- 它们的总和不等于 10(如果不是因为缩放错误,则不等于 1)。随着样本量的增加,错误变得更加明显:大约有。 5% 的观察结果未包括在内。
我相信我实现了公式 1:1,因此我真的不明白错误在哪里。
【问题讨论】:
标签: algorithm machine-learning julia