【发布时间】:2015-08-18 00:50:48
【问题描述】:
在尝试将一些代码从 Matlab 移植到 R 时,我遇到了问题。代码的要点是生成一个 2D 核密度估计,然后使用该估计进行一些简单的计算。在 Matlab 中,KDE 计算是使用函数ksdensity2d.m 完成的。在 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)
给出的答案是 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)
}
一个简单的检查,看看带宽的差异是否是导致结果差异的原因
kk <- kde2d(x, y, h=c(30, 1.5)*4, n=100, lims=c(1000, 2000, -12, 12))
sum(kk$z)
给出 0.3768013(与 Matlab 答案相同)。
那么我的问题是:为什么 kde2d 将带宽分成四份? (或者为什么不 ksdensity2d?)
【问题讨论】:
标签: r matlab kernel-density