knn_density: Non-parametric multivariate density estimator

Description Usage Arguments Value See Also Examples

View source: R/knnStats.R

Description

Standard k-nearest neighbor (knn) density estimator

P(Xi) ~ k / (N Vi)

where N is the number of observations and Vi the volume of a sphere of radius equal to the distance between Xi and its k-nearest neighbor.

Usage

1
knn_density(x, k, xref = NULL, smoothing = TRUE, nn_alg = "kd_tree")

Arguments

x

numeric matrix representing multivariate data where rows = observations and columns = measurement conditions (query data).

k

number of nearest neighbors which has equivalent effects as the usual bandwidth or smoothing parameters (larger k => smoother results).

xref

numeric matrix representing multivariate data where rows = observations and columns = measurement conditions (optional reference data).

smoothing

logical value activating an additional local average smoothing of the estimated density (default = TRUE, active).

nn_alg

nearest neighbor searching algorithm (default = "kd_tree"). See get.knn for further explanations.

Value

knn_density returns a numeric vector.

See Also

knn_mean

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
## Not run: 

n1 <- 10000
n2 <- 20000
g <- c(rep(1, n1), rep(2, n2))
x <- c(rnorm(n1, 0, 1), rnorm(n2, 0, 5))

o <- order(x)
x <- x[o]
g <- g[o]

dt <- knn_density(x, k = 50)
d1 <- knn_density(x, xref = x[g == 1], k = 50)
d2 <- knn_density(x, xref = x[g == 2], k = 50)

clr <- c(
  dt        = grey(0.0, 0.6),
  d1        = rgb(1.0, 0.5, 0.0, 0.6),
  d2        = rgb(0.0, 0.5, 1.0, 0.6),
  `d1 + d2` = rgb(1.0, 0.0, 0.0, 0.6)
)

plot(0, type = 'n', xlim = range(x), ylim = range(dt, d1, d2, d1 + d2))
par(lwd = 1.5)
lines(x, d1 + d2, col = clr[4])
lines(x, dt, col = clr["dt"])
lines(x, d1, col = clr["d1"])
lines(x, d2, col = clr["d2"])
legend("topright", legend = names(clr), fill = clr, bty = "n")


## End(Not run)

benja0x40/QuickShift documentation built on Jan. 22, 2021, 7:43 p.m.