mkr*_*mkr 5 matlab r kernel-density
尝试将一些代码从Matlab移植到RI时遇到了问题.代码的要点是产生2D核密度估计,然后使用估计进行一些简单的计算.在Matlab中,使用函数ksdensity2d.m完成KDE计算.在R中,KDE计算使用MASS包中的kde2d完成.所以我想说我想计算KDE并只是添加值(这不是我打算做的,但它可以达到这个目的).在R中,这可以通过
library(MASS)
set.seed(1009)
x <- sample(seq(1000, 2000), 100, replace=TRUE)
y <- sample(seq(-12, 12), 100, replace=TRUE)
kk <- kde2d(x, y, h=c(30, 1.5), n=100, lims=c(1000, 2000, -12, 12))
sum(kk$z)
Run Code Online (Sandbox Code Playgroud)
给出答案0.3932732.在Matlab中使用ksdensity2d时,使用相同的确切数据和条件,答案为0.3768.从查看kde2d的代码,我注意到带宽除以4
kde2d <- function (x, y, h, n = 25, lims = c(range(x), range(y)))
{
nx <- length(x)
if (length(y) != nx)
stop("data vectors must be the same length")
if (any(!is.finite(x)) || any(!is.finite(y)))
stop("missing or infinite values in the data are not allowed")
if (any(!is.finite(lims)))
stop("only finite values are allowed in 'lims'")
n <- rep(n, length.out = 2L)
gx <- seq.int(lims[1L], lims[2L], length.out = n[1L])
gy <- seq.int(lims[3L], lims[4L], length.out = n[2L])
h <- if (missing(h))
c(bandwidth.nrd(x), bandwidth.nrd(y))
else rep(h, length.out = 2L)
if (any(h <= 0))
stop("bandwidths must be strictly positive")
h <- h/4
ax <- outer(gx, x, "-")/h[1L]
ay <- outer(gy, y, "-")/h[2L]
z <- tcrossprod(matrix(dnorm(ax), , nx), matrix(dnorm(ay),
, nx))/(nx * h[1L] * h[2L])
list(x = gx, y = gy, z = z)
}
Run Code Online (Sandbox Code Playgroud)
然后,简单检查以确定带宽差异是否是结果差异的原因
kk <- kde2d(x, y, h=c(30, 1.5)*4, n=100, lims=c(1000, 2000, -12, 12))
sum(kk$z)
Run Code Online (Sandbox Code Playgroud)
得到0.3768013(与Matlab答案相同).
所以我的问题是:为什么kde2d将带宽除以4?(或者为什么没有ksdensity2d?)
在镜像的github 源代码中,第 31-35 行:
if (any(h <= 0))
stop("bandwidths must be strictly positive")
h <- h/4 # for S's bandwidth scale
ax <- outer(gx, x, "-" )/h[1L]
ay <- outer(gy, y, "-" )/h[2L]
Run Code Online (Sandbox Code Playgroud)
以及kde2d()的帮助文件,建议查看带宽的帮助文件。说的是:
...它们都按密度的宽度参数缩放,因此给出的答案是四倍大。
但为什么?
Density()表示该width参数的存在是为了与 S(R 的前身)兼容。源码中的评论如下density():
## S has width equal to the length of the support of the kernel
## except for the gaussian where it is 4 * sd.
## R has bw a multiple of the sd.
Run Code Online (Sandbox Code Playgroud)
默认是高斯分布。当bw参数未指定并且width是时,width被替换为例如。
library(MASS)
set.seed(1)
x <- rnorm(1000, 10, 2)
all.equal(density(x, bw = 1), density(x, width = 4)) # Only the call is different
Run Code Online (Sandbox Code Playgroud)
然而,因为kde2d()显然是为了与 S 保持兼容而编写的(我想它最初是为 S 编写的,因为它是在 MASS 中),所以所有内容最终都会除以四。在翻阅 MASS 书的相关部分(大约第 126 页)后,他们似乎可能选择了四个来在数据的平滑性和保真度之间取得平衡。
总之,我的猜测是kde2d()除以四以与 MASS 的其余部分(以及最初为 S 编写的其他内容)保持一致,并且您处理事情的方式看起来不错。