Multivariate density estimation

Kernel density estimation with a full bandwidth matrix, in robustmodels.density. The estimate at x averages normal densities centred at the observations, f(x) = mean_i phi_H(x - X_i). The bandwidth matrix H sets the amount and the orientation of the smoothing. A full H can smooth along the directions of correlated data, which a scalar or diagonal bandwidth cannot. It is selected from the data for the density or for one of its derivatives.

Use

>>> import numpy as np
>>> from robustmodels.density import KernelDensity
>>> rng = np.random.default_rng(1)
>>> X = np.vstack(
...     [
...         rng.multivariate_normal([0, 0], [[1, 0.6], [0.6, 1]], 250),
...         rng.multivariate_normal([3, 3], [[0.4, -0.2], [-0.2, 0.4]], 150),
...     ]
... )
>>> kde = KernelDensity().fit(X)  # plug-in bandwidth
>>> kde.bandwidth_.round(3).tolist()
[[0.109, 0.074], [0.074, 0.104]]
>>> np.exp(kde.score_samples([[0, 0], [3, 3], [1.5, 1.5]])).round(3).tolist()
[0.151, 0.083, 0.031]

score_samples returns the log density, as scikit-learn’s density estimators do. A highest density region of probability p is the smallest region with that probability: the set {x : f(x) >= level}. hdr_level estimates its level by a quantile of the estimate at the observations (Hyndman 1996). Separate regions of the same probability show separate modes.

>>> kde.hdr_level([0.25, 0.5, 0.75]).round(4).tolist()
[0.0975, 0.074, 0.046]

import numpy as np
from robustmodels import plots
from robustmodels.density import KernelDensity

rng = np.random.default_rng(1)
X = np.vstack([
    rng.multivariate_normal([0, 0], [[1, 0.6], [0.6, 1]], 250),
    rng.multivariate_normal([3, 3], [[0.4, -0.2], [-0.2, 0.4]], 150),
])
plots.hdr_plot(KernelDensity().fit(X))

(png, svg)

Filled 25%, 50% and 75% highest density regions of a two-mode sample.

Density derivatives

gradient and hessian differentiate the estimate. Derivatives need more smoothing than the density: with deriv_order=1 or 2 the bandwidth is selected for the gradient or the Hessian (Chacón & Duong 2013). The Hessian is negative definite near a mode and has eigenvalues of both signs at a saddle between modes, which locates modes and the valleys between them.

>>> hessian = KernelDensity(deriv_order=2).fit(X).hessian([[0, 0], [1.5, 1.5]])
>>> [np.linalg.eigvalsh(h).round(3).tolist() for h in hessian]
[[-0.461, -0.083], [-0.042, 0.073]]

Comparing two samples

kde_permutation_test compares two independent samples with a common bandwidth. It integrates the squared difference of their Gaussian KDEs by evaluating Gaussian kernels with twice that bandwidth matrix. This is a squared maximum mean discrepancy. Under the null, the pooled observations are exchangeable. The bandwidth is selected from the pooled data and held fixed as the labels are reassigned.

>>> from robustmodels.density import kde_permutation_test
>>> kde_permutation_test([-2, -1, 0, 1], [2, 3, 4, 5], n_resamples=np.inf).pvalue
0.02857142857142857

When the budget covers all assignments, the p-value is exact up to floating-point precision. With random assignments, the observed assignment is included in the count. Pass a bandwidth chosen independently of the labels to use a fixed matrix, including when the pooled covariance is singular. The kernel matrix and each statistic use quadratic resources in the pooled sample size.

Comparing at several scales

kde_multiscale_test uses the same base bandwidth and compares the samples at several smoothing scales. A multiplier s uses the matrix s²H. Each scale’s discrepancy is standardized using the same label assignments. The test ranks the observed maximum against the maxima of those assignments, so the p-value accounts for comparing at several scales. The returned statistic is this standardized maximum and is dimensionless.

>>> from robustmodels.density import kde_multiscale_test
>>> result = kde_multiscale_test([-2, -1, 0, 1], [2, 3, 4, 5], n_resamples=np.inf)
>>> round(result.pvalue, 4)
0.0286

The function counts ties in the upper tail. With a random permutation budget, it includes the observed assignment when standardizing each scale and when computing the p-value. Choose the bandwidth and the scales independently of the labels. The joint calibration applies to two independent samples under the null of a common distribution. Each additional scale adds a quadratic pass per assignment. One Gram matrix is reused across scales.

The following pilot compares the public single-bandwidth and multiscale functions. Each scenario used 300 independent pairs of samples of sizes 35 and 45 in two dimensions, with 199 shared random assignments per replicate and a nominal level of 5%. Both functions used their default bandwidths and the multiscale function used its five default scales.

Data for the second sample

Single bandwidth

Multiscale

Both samples standard normal

22/300

19/300

Shift of 0.65 in the first coordinate

107/300

161/300

Twice the standard deviation in the second coordinate

170/300

135/300

Bimodal first coordinate with the same population mean and variance

142/300

184/300

The pilot used np.random.default_rng(3219) for all four scenarios in order. In each replicate it drew the first and then the second sample from the standard normal, applied the change in the table, and drew one shared seed with int(rng.integers(2**32)). For bimodality it multiplied the second sample’s first coordinate by 0.25 and added independent signs from rng.choice([-1, 1], size=45) times sqrt(1 - 0.25**2). The exact binomial 95% intervals under the null are 4.65–10.89% and 3.86–9.71%. The relative power varies across these alternatives.

Normal calibration

kde_test estimates the population integrated squared difference with separate bandwidths (Duong, Goud & Schauer 2012). It can detect differences in location, spread, shape or number of modes.

>>> from robustmodels.density import kde_test
>>> one_mode = rng.multivariate_normal([0, 0], [[1, 0.6], [0.6, 1]], 300)
>>> result = kde_test(X, one_mode)
>>> round(result.z, 2), round(result.pvalue, 4)
(3.43, 0.0003)

The p-value comes from an asymptotic normal approximation. The statistic can be negative when the bandwidths differ. The test raises an error when the variance used for calibration is numerically zero. For finite-sample calibration under exchangeability, use kde_permutation_test.

Choosing the bandwidth

  • "plugin" (default) minimizes an estimate of the asymptotic mean integrated squared error over all positive definite matrices (Chacón & Duong 2010). It is the usual choice.

  • "scv", smoothed cross-validation (Duong & Hazelton 2005; Chacón & Duong 2011), replaces the asymptotic bias by the exact bias of presmoothed data. It tends to smooth more, which helps when the plug-in estimate looks noisy.

  • A number h gives H = h^2 I, and a matrix is used as H.

Both selectors optimize their criteria on the sphered data with a normal-reference pilot. The resulting selectors are affine equivariant: transforming the data by a matrix A transforms H into A H A'. They sum over all pairs of observations, so they take O(n^2) time; a few thousand observations take seconds.

Numerical checks and sources

The derivatives of the normal kernel needed by the selectors are evaluated through moments of quadratic forms of a normal vector, computed exactly from their cumulants, instead of the vectors of all partial derivatives used by R’s ks. The tests compare these moments with Hermite polynomials in one dimension and with exact Gauss–Hermite quadrature in two. The estimate integrates to one, its gradient and Hessian agree with finite differences, and the permutation statistic agrees with independent quadrature of the squared density difference. Its p-value agrees with enumeration of all assignments for a small sample with unequal group sizes and ties. Both selectors are affine equivariant.

On frozen data, R’s ks 1.15 gives the same density, gradient, Hessian and highest density levels (to 1e-12), and the same two-sample statistic and p-value for the same bandwidths. Its Hpi and Hscv with pilot = "dscalar" and no binning give the same pilot bandwidths, and bandwidth matrices within 1e-3. The criterion is lower at our matrices, because ks stops its search earlier. Other differences from ks:

  • ks’s default pilot for the density of two variables is the SAMSE pilot, and ks bins large samples; robustmodels uses the dscalar pilot in every case and no binning.

  • In kde_test, ks evaluates the density gradient at the sample means by interpolating a grid estimate; robustmodels evaluates it exactly. ks chooses each bandwidth by minimizing a mean squared error whose minimizers form a continuum; robustmodels takes the unique minimizer proportional to the sample covariance.

  • In one dimension ks uses the univariate selectors hpi and hscv; robustmodels uses the same matrix selectors in every dimension.

Sources are Wand & Jones (1993), Chacón & Duong (2010, 2011, 2013), Chacón, Duong & Wand (2011), Duong & Hazelton (2005), Hyndman (1996) and Duong, Goud & Schauer (2012); see the method references.

Reference

class KernelDensity(bandwidth='plugin', *, deriv_order=0)[source]

Kernel density estimator with a normal kernel and a full bandwidth matrix.

The estimate at x is f(x) = mean_i phi_H(x - X_i), with phi_H the normal density with covariance H. A full H smooths along the directions of the data, which a scalar or diagonal bandwidth cannot (Wand & Jones 1993). By default H minimizes a plug-in estimate of the mean integrated squared error of the density or of its derivative of order deriv_order: derivatives need more smoothing than the density.

Parameters:
  • bandwidth ({"plugin", "scv"}, float or array-like, default "plugin") – "plugin" and "scv" select H with plugin_bandwidth() or scv_bandwidth(); a number h gives H = h^2 I, and a matrix of shape (n_features, n_features) is used as H.

  • deriv_order ({0, 1, 2}, default 0) – Derivative the selected bandwidth is optimal for: the density (0), its gradient (1) or its Hessian (2).

bandwidth_

Bandwidth matrix H.

Type:

ndarray of shape (n_features, n_features)

X_

Training data.

Type:

ndarray of shape (n_samples, n_features)

References

Wand, M. P. and Jones, M. C. (1993). Comparison of smoothing parameterizations in bivariate kernel density estimation. Journal of the American Statistical Association, 88(422), 520-528.

Chacón, J. E. and Duong, T. (2018). Multivariate Kernel Smoothing and Its Applications. Chapman and Hall/CRC.

Examples

>>> import numpy as np
>>> from robustmodels.density import KernelDensity
>>> rng = np.random.default_rng(0)
>>> X = rng.multivariate_normal([0, 0], [[1, 0.8], [0.8, 1]], size=300)
>>> kde = KernelDensity().fit(X)
>>> kde.bandwidth_.round(3).tolist()  # oriented along the correlation
[[0.087, 0.064], [0.064, 0.069]]
>>> np.exp(kde.score_samples([[0, 0], [1, -1]])).round(3).tolist()
[0.182, 0.004]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

score_samples(X)[source]

Log density at each row of X.

gradient(X)[source]

Gradient of the density estimate at each row of X, shape (n_queries, n_features).

hessian(X)[source]

Hessian of the density estimate at each row of X.

Returns an array of shape (n_queries, n_features, n_features).

hdr_level(prob)[source]

Density level whose upper level set is the prob highest density region.

The region {x : f(x) >= level} has probability prob; the level is estimated by the 1 - prob quantile of the density estimate at the training observations (Hyndman 1996), as R’s ks::contourLevels. prob may be a number or an array of numbers in (0, 1).

Hyndman, R. J. (1996). Computing and graphing highest density regions. The American Statistician, 50(2), 120-126.

plugin_bandwidth(X, deriv_order=0)[source]

Plug-in bandwidth matrix of a normal kernel (Chacón & Duong 2010, 2013).

Minimizes over all symmetric positive definite H the asymptotic mean integrated squared error of the estimate of the derivative of order r,

n^-1 |H|^-1/2 2^-(d+r) pi^-d/2 nu_r(H^-1) + (-1)^r / 4 (vec I_{d^r} (x) vec H (x) vec H)' psi_{2r+4},

where nu_r(A) = E[(Z'AZ)^r] for standard normal Z and the integrated density derivative psi_{2r+4} is estimated with a scalar pilot bandwidth on the sphered data, chosen in two stages from a normal reference (the dscalar pilot of Chacón & Duong 2013). The result is affine equivariant: transforming X by a matrix A gives A H A'.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Sample with a nonsingular covariance matrix.

  • deriv_order ({0, 1, 2}, default 0) – Order of the derivative to estimate: density, gradient or Hessian.

Return type:

ndarray of shape (n_features, n_features)

Notes

The double sums over pairs take O(n^2) time; R’s ks::Hpi bins the data instead for large samples, and its default pilot for the density of two variables is the SAMSE pilot (pass pilot = "dscalar" to compare).

References

Chacón, J. E. and Duong, T. (2010). Multivariate plug-in bandwidth selection with unconstrained pilot bandwidth matrices. Test, 19(2), 375-398.

Chacón, J. E. and Duong, T. (2013). Data-driven density derivative estimation, with applications to nonparametric clustering and bump hunting. Electronic Journal of Statistics, 7, 499-532.

Chacón, J. E., Duong, T. and Wand, M. P. (2011). Asymptotics for general multivariate kernel density derivative estimators. Statistica Sinica, 21(2), 807-840.

scv_bandwidth(X, deriv_order=0)[source]

Smoothed cross-validation bandwidth matrix of a normal kernel (Chacón & Duong 2011).

Minimizes over all symmetric positive definite H the variance term of plugin_bandwidth() plus the smoothed estimate of the integrated squared bias,

(-1)^r n^-2 sum_ij (vec I_{d^r})' D^{2r} L(X_i - X_j), L = phi_{2H+2G} - 2 phi_{H+2G} + phi_{2G},

which replaces the asymptotic bias by its exact value for the data presmoothed with the pilot G = g^2 I on the sphered data (Duong & Hazelton 2005), with the dscalar pilot of Chacón & Duong (2013).

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Sample with a nonsingular covariance matrix.

  • deriv_order ({0, 1, 2}, default 0)

Return type:

ndarray of shape (n_features, n_features)

Notes

Each evaluation of the criterion sums over all pairs, so the selection takes O(n^2) time per step of the minimization.

References

Duong, T. and Hazelton, M. L. (2005). Cross-validation bandwidth matrices for multivariate kernel density estimation. Scandinavian Journal of Statistics, 32(3), 485-506.

Chacón, J. E. and Duong, T. (2011). Unconstrained pilot selectors for smoothed cross-validation. Australian & New Zealand Journal of Statistics, 53(3), 331-351.

kde_test(X1, X2)[source]

Two-sample test of equal densities by kernel estimates (Duong, Goud & Schauer 2012).

The statistic estimates the integrated squared difference T = int (f1 - f2)^2 = psi_1 + psi_2 - psi_12 - psi_21, where psi_1 = n1^-2 sum_ij phi_H1(X1_i - X1_j) estimates int f1^2 and psi_12 = (n1 n2)^-1 sum_ij phi_H1(X1_i - X2_j) estimates int f1 f2. Under the hypothesis f1 = f2, T is asymptotically normal with mean (n1^-1 |H1|^-1/2 + n2^-1 |H2|^-1/2) phi(0) and the variance of the reference, estimated from the density gradient at the sample means; large values reject. Hj = h_j^2 S_j (S_j the sample covariance) with h_j minimizing the asymptotic mean squared error of psi_j, estimated with a normal reference pilot.

Parameters:
  • X1 (array-like of shape (n1, n_features) and (n2, n_features)) – The samples; one-dimensional arrays are samples of one variable.

  • X2 (array-like of shape (n1, n_features) and (n2, n_features)) – The samples; one-dimensional arrays are samples of one variable.

Returns:

statistic (T), z (standardized T) and the upper-tail normal pvalue.

Return type:

KDETestResult

Notes

With different bandwidths, the statistic estimates a population squared distance and can be negative. It is not the exact integral between two fitted KDEs. If the estimated variance is numerically zero, the function raises ValueError. See kde_permutation_test() for an alternative that uses a common bandwidth and permutation calibration.

R’s ks::kde.test minimizes the same mean squared error over all matrices H, whose minimizers form a continuum; it returns the one its optimizer reaches. The bandwidth proportional to S is the unique minimizer of that form. Passing these bandwidths to kde.test gives the same statistic and p-value.

References

Duong, T., Goud, B. and Schauer, K. (2012). Closed-form density-based framework for automatic detection of cellular morphology changes. Proceedings of the National Academy of Sciences, 109(22), 8382-8387.

Examples

>>> import numpy as np
>>> from robustmodels.density import kde_test
>>> rng = np.random.default_rng(0)
>>> X1 = rng.normal(size=(150, 2))
>>> X2 = rng.normal(size=(150, 2)) * [1, 2]  # more spread in the second variable
>>> result = kde_test(X1, X2)
>>> round(result.z, 2), round(result.pvalue, 4)
(2.21, 0.0134)
kde_permutation_test(X1, X2, *, bandwidth=None, n_resamples=999, random_state=None)[source]

Compare two independent samples by permuting labels of a pooled Gaussian KDE.

The statistic is the integrated squared difference of two KDEs with a common bandwidth matrix H. Products of Gaussian kernels integrate to a Gaussian kernel with bandwidth 2H, so the statistic is also a squared maximum mean discrepancy (Gretton et al. 2012).

Parameters:
  • X1 (array-like) – Samples of shape (n_samples, n_features), or 1-D for one variable.

  • X2 (array-like) – Samples of shape (n_samples, n_features), or 1-D for one variable.

  • bandwidth (float or array-like, optional) – A standard deviation or positive definite matrix, as for KernelDensity. The default is the normal reference bandwidth of the pooled sample, which requires nonsingular pooled covariance.

  • n_resamples (int or np.inf, default 999) – Permutation budget. Enumerate all assignments if the budget permits.

  • random_state (int or numpy.random.Generator, optional) – Seed or generator for the random label assignments.

Returns:

Integrated squared difference and upper-tail permutation p-value.

Return type:

KDEPermutationResult

Notes

The common bandwidth is held fixed across assignments. Choose it without using the labels to preserve the finite-sample permutation calibration under exchangeability. Randomized p-values include the observed assignment in the numerator and denominator. The method stores an N by N kernel matrix and takes quadratic time in the pooled size N per assignment.

References

Gretton, A., Borgwardt, K. M., Rasch, M. J., Schölkopf, B. and Smola, A. (2012). A kernel two-sample test. Journal of Machine Learning Research, 13(25), 723-773.

kde_multiscale_test(X1, X2, *, bandwidth=None, scales=(0.25, 0.5, 1.0, 2.0, 4.0), n_resamples=999, random_state=None)[source]

Compare two independent samples at several Gaussian kernel bandwidths.

For each scale s of the pooled bandwidth matrix H, compute the squared discrepancy of the two KDEs with bandwidth s**2 * H. Standardize the discrepancies within each scale, then take their maximum. The same label assignments are used at every scale so one permutation calibration accounts for the search across scales.

Parameters:
  • X1 (array-like) – Samples of shape (n_samples, n_features), or 1-D for one variable.

  • X2 (array-like) – Samples of shape (n_samples, n_features), or 1-D for one variable.

  • bandwidth (float or array-like, optional) – Common base standard deviation or positive definite bandwidth matrix, as in kde_permutation_test(). The default is the normal reference bandwidth of the pooled sample, which requires nonsingular covariance.

  • scales (array-like, default (0.25, 0.5, 1, 2, 4)) – Nonempty sequence of finite positive multipliers of the base standard deviation. Choose the bandwidth and scales without using the labels.

  • n_resamples (int or np.inf, default 999) – Permutation budget. Enumerate all assignments if the budget permits.

  • random_state (int, numpy.random.Generator or None, optional) – Seed or generator for the shared label assignments.

Returns:

Maximum standardized discrepancy and its upper-tail permutation p-value. If every scale has numerically constant scores, return (0, 1).

Return type:

KDEMultiscaleResult

Notes

The center and standard deviation of each scale are computed over all enumerated assignments, or over the random assignments plus the observed assignment. Constant scales are omitted. This symmetric treatment keeps the row statistics exchangeable when the labels are exchangeable. The calibration includes ties in the upper tail.

The implementation keeps one Gram matrix at a time. With N pooled observations, S scales and B assignments, the time for evaluating the discrepancies is O(S B N**2). The distance matrix, Gram matrix, and permutation scores use O(N**2 + S B) storage.

References

Schrab, A., Kim, I., Albert, M., Laurent, B., Guedj, B. and Gretton, A. (2023). MMD aggregated two-sample test. Journal of Machine Learning Research, 24(194), 1-81. Aggregates kernels with a different statistic.

Hemerik, J. and Goeman, J. (2018). Exact testing with random permutations. TEST, 27, 811-825.

class KDETestResult(statistic: float, z: float, pvalue: float)[source]

Result of kde_test().

class KDEPermutationResult(statistic: float, pvalue: float)[source]

Result of kde_permutation_test().

class KDEMultiscaleResult(statistic: float, pvalue: float)[source]

Maximum standardized kernel distance and its joint permutation p-value.