deepbox/stats
Distributions & KDE
Probability distributions with pdf, cdf, ppf and moments, confidence intervals, and Gaussian kernel density estimation.
- Probability
- Intervals
Overview
- Factories such as
norm(loc, scale),poisson(mu)andbinom(n, p)return objects withpdf(orpmf),cdf,sf,ppf,isf,rvs,mean,variance,stdandmedian. Continuous distributions also haveentropy.rvs(size)returns a plain array. - Parameters follow the textbook form, which is not always SciPy's.
expon(rate)andgamma(shape, rate)take a rate where SciPy takesscale = 1 / rate.lognorm(mu, sigma)takes the mean and standard deviation of the underlying normal.weibull(k, lam)andpareto(alpha, xm)take shape and scale. Each function's reference entry shows the SciPy equivalent. gaussianKde(data, { bwMethod })builds aGaussianKDE. A number passed asbwMethodis the absolute bandwidth, not SciPy's factor that multiplies the data's standard deviation.weightsare supported.- The confidence interval functions take plain number arrays and return
{ lower, upper, mean, marginOfError, confidenceLevel }.meanConfidenceIntervaluses the t distribution and needs at least two values.meanConfidenceIntervalZtakes a known standard deviation,proportionConfidenceIntervaluses the Wald or Wilson method, andmeanDiffConfidenceIntervalcompares two samples. - Special functions are accurate to about 1e-14, and the survival functions
sfandisfstay accurate in the tails, where1 - cdf(x)loses precision.
ConfidenceInterval
interfaceResult of a confidence interval computation.
readonly lower: numberLower bound of the interval
readonly upper: numberUpper bound of the interval
readonly mean: numberPoint estimate (center)
readonly marginOfError: numberMargin of error
readonly confidenceLevel: numberConfidence level used
ContinuousDistribution
interfaceA continuous probability distribution with a fixed set of parameters.
Create one with a factory such as norm or gamma. pdf, cdf and sf return NaN for a NaN argument. ppf throws for p outside [0, 1] (including NaN) and returns the end of the support for p equal to 0 or 1.
pdf(x: number): numberProbability density at
x.cdf(x: number): numberCumulative distribution function, P(X <= x).
ppf(p: number): numberPercent point function (quantile, the inverse of
cdf) forpin [0, 1].sf(x: number): numberSurvival function, P(X > x), accurate in the upper tail where
1 - cdf(x)is not.isf(q: number): numberInverse survival function: the
xwithsf(x) = q, forqin [0, 1].rvs(size?: number): number[]Draws
size(default 1) independent random variates.mean(): numberExpected value (NaN or Infinity where it does not exist).
variance(): numberVariance (NaN or Infinity where it does not exist).
std(): numberStandard deviation, the square root of
variance().median(): numberMedian,
ppf(0.5).entropy(): numberDifferential entropy in nats.
DiscreteDistribution
interfaceA discrete probability distribution on the integers with a fixed set of parameters.
Create one with a factory such as binom or poisson. pmf is 0 at non-integer arguments. cdf and sf accept any real x (they use floor(x)). ppf returns the smallest integer k with cdf(k) >= p, and throws for p outside [0, 1] (including NaN).
pmf(k: number): numberProbability mass at
k.cdf(x: number): numberCumulative distribution function, P(X <= x).
ppf(p: number): numberPercent point function: the smallest integer
kwithcdf(k) >= p, forpin [0, 1].sf(x: number): numberSurvival function, P(X > x), accurate in the upper tail where
1 - cdf(x)is not.isf(q: number): numberInverse survival function: the smallest integer
kwithsf(k) <= q, forqin [0, 1].rvs(size?: number): number[]Draws
size(default 1) independent random variates.mean(): numberExpected value.
variance(): numberVariance.
std(): numberStandard deviation, the square root of
variance().median(): numberMedian,
ppf(0.5).
BandwidthMethod
typeBandwidth selection method: "scott", "silverman", or an explicit bandwidth, which is the standard deviation of the Gaussian kernel in the units of the data.
Unlike SciPy, where a number is a factor that is multiplied by the standard deviation of the data, a number here is the absolute bandwidth.
type BandwidthMethod = "scott" | "silverman" | number;GaussianKDEOptions
interfaceOptions for gaussian_kde.
bwMethod?: BandwidthMethodBandwidth selection method or explicit bandwidth value.
bw_method?: BandwidthMethoddeprecatedBandwidth selection method or explicit bandwidth value.
weights?: number[] | Float64ArrayNon-negative weights of the data points (normalized to sum to one).
GaussianKDE
Gaussian kernel density estimator.
Represents a kernel-density estimate using Gaussian kernels. The estimator is fitted on a 1D dataset and can evaluate the estimated density at arbitrary points.
Members (12)
constructor(data: Float64Array, bandwidth: number, weights?: Float64Array | number[])readonly dataset: Float64ArrayThe fitted dataset (a copy of the input).
readonly nData: numberNumber of data points.
readonly bandwidth: numberThe bandwidth (standard deviation of the Gaussian kernel).
readonly weights: Float64Array | undefinedNormalized weights of the data points, or
undefinedfor equal weights.readonly neff: numberEffective number of data points,
1 / sum(w^2)(equal tonDatawithout weights).evaluate(points: number[] | Float64Array): Float64ArrayEvaluate the estimated density at the given points.
pdf(points: number[] | Float64Array): Float64ArrayEvaluate the estimated density at the given points.
logDensity(points: number[] | Float64Array): Float64ArrayEvaluate the log-density at the given points.
logpdf(points: number[] | Float64Array): Float64ArrayEvaluate the log-density at the given points.
integrateBox1d(low: number, high: number): numberIntegrate the estimated density over the interval
[low, high].integrate(): numberIntegrate the estimated density over the entire real line.
meanConfidenceInterval
function meanConfidenceInterval(data: readonly number[], confidenceLevel?: number): ConfidenceInterval;Compute a confidence interval for the mean of a sample using the t-distribution.
Use this when the population standard deviation is unknown (most common case).
Parameters
datareadonly number[]- Array of sample values (at least 2)
confidenceLeveloptionalnumber- Confidence level, strictly between 0 and 1 (default 0.95 for 95%)
Returns
ConfidenceIntervalConfidence interval result
Throws
InvalidParameterErrorIfdatahas fewer than 2 values orconfidenceLevelis not strictly between 0 and 1
import { meanConfidenceInterval } from 'deepbox/stats'; const data = [2.3, 2.5, 2.1, 2.4, 2.6, 2.2];const ci = meanConfidenceInterval(data, 0.95);console.log(`95% CI: [${ci.lower.toFixed(3)}, ${ci.upper.toFixed(3)}]`);meanConfidenceIntervalZ
function meanConfidenceIntervalZ(data: readonly number[], popStd: number, confidenceLevel?: number): ConfidenceInterval;Compute a confidence interval for the mean using a known population standard deviation (z-interval).
Parameters
datareadonly number[]- Array of sample values (at least 1)
popStdnumber- Known population standard deviation (positive and finite)
confidenceLeveloptionalnumber- Confidence level, strictly between 0 and 1 (default 0.95)
Returns
ConfidenceIntervalConfidence interval result
Throws
InvalidParameterErrorIfdatais empty,popStdis not a positive finite number, orconfidenceLevelis not strictly between 0 and 1
import { meanConfidenceIntervalZ } from 'deepbox/stats'; const ci = meanConfidenceIntervalZ([10, 12, 11, 13, 9], 2.0, 0.99);meanDiffConfidenceInterval
function meanDiffConfidenceInterval(data1: readonly number[], data2: readonly number[], confidenceLevel?: number, equalVar?: boolean): ConfidenceInterval;Compute a confidence interval for the difference of two means (independent samples).
By default uses Welch's t interval for unequal variances, with the (fractional) Welch-Satterthwaite degrees of freedom, as scipy.stats.ttest_ind(..., equal_var=False).confidence_interval() does. With equalVar = true it uses the pooled-variance interval with n1 + n2 - 2 degrees of freedom.
Parameters
data1readonly number[]- First sample (at least 2 values)
data2readonly number[]- Second sample (at least 2 values)
confidenceLeveloptionalnumber- Confidence level, strictly between 0 and 1 (default 0.95)
equalVaroptionalboolean- Assume equal population variances and pool them (default false)
Returns
ConfidenceIntervalConfidence interval for (mean1 - mean2)
Throws
InvalidParameterErrorIf either sample has fewer than 2 values orconfidenceLevelis not strictly between 0 and 1
import { meanDiffConfidenceInterval } from 'deepbox/stats'; const ci = meanDiffConfidenceInterval([5.1, 4.9, 5.6, 5.8], [4.2, 4.8, 4.4, 5.0], 0.95);proportionConfidenceInterval
function proportionConfidenceInterval(successes: number, total: number, confidenceLevel?: number, method?: ProportionIntervalMethod): ConfidenceInterval;Compute a confidence interval for a proportion.
The default is the Wald (normal approximation) interval, p ± z·sqrt(p(1-p)/n), which has poor coverage for small samples or proportions near 0 or 1 (it collapses to zero width when p is 0 or 1). Pass "wilson" for the Wilson score interval, which does not have those problems.
Parameters
successesnumber- Number of successes (between 0 and
total) totalnumber- Total number of trials (at least 1)
confidenceLeveloptionalnumber- Confidence level, strictly between 0 and 1 (default 0.95)
methodoptionalProportionIntervalMethod"wald"(default) or"wilson"
Returns
ConfidenceIntervalConfidence interval result (mean is the sample proportion; marginOfError is the half-width of the interval before clipping to [0, 1])
Throws
InvalidParameterErrorIftotalis not at least 1,successesis outside[0, total],confidenceLevelis not strictly between 0 and 1, ormethodis unknown
import { proportionConfidenceInterval } from 'deepbox/stats'; const ci = proportionConfidenceInterval(45, 100, 0.95);console.log(`Proportion: ${ci.mean}, 95% CI: [${ci.lower}, ${ci.upper}]`); const wilson = proportionConfidenceInterval(0, 20, 0.95, "wilson");beta
function beta(a: number, b: number): ContinuousDistribution;Beta distribution.
Matches scipy.stats.beta(a, b).
Parameters
anumber- Alpha shape parameter, must be a finite number > 0
bnumber- Beta shape parameter, must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfaorbis not a finite number > 0
import { beta } from 'deepbox/stats'; beta(2, 5).mean(); // 0.2857142857142857binom
function binom(n: number, p: number): DiscreteDistribution;Binomial distribution.
Matches scipy.stats.binom(n, p).
Parameters
nnumber- Number of trials (non-negative integer)
pnumber- Probability of success per trial, in [0, 1]
Returns
DiscreteDistributionDistribution object
Throws
InvalidParameterErrorIfnis not a non-negative integer orpis not in [0, 1]
import { binom } from 'deepbox/stats'; binom(10, 0.5).pmf(5); // 0.24609375cauchy
function cauchy(x0?: number, gammaParam?: number): ContinuousDistribution;Cauchy distribution.
Matches scipy.stats.cauchy(loc=x0, scale=gammaParam). Mean and variance are NaN.
Parameters
x0optionalnumber- Location parameter (default 0)
gammaParamoptionalnumber- Scale parameter (default 1), must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfx0is not finite orgammaParamis not a finite number > 0
import { cauchy } from 'deepbox/stats'; cauchy(0, 1).ppf(0.75); // 1.0000000000000002 (tan of π/4)chi2
function chi2(df: number): ContinuousDistribution;Chi-squared distribution.
Matches scipy.stats.chi2(df).
Parameters
dfnumber- Degrees of freedom, must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfdfis not a finite number > 0
import { chi2 } from 'deepbox/stats'; chi2(3).sf(100); // upper-tail p-value, about 1.1e-21, without cancellationexpon
function expon(rate?: number): ContinuousDistribution;Exponential distribution.
Matches scipy.stats.expon(scale=1 / rate).
Parameters
rateoptionalnumber- Rate parameter λ (default 1), must be a finite number > 0. Mean = 1/λ
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfrateis not a finite number > 0
import { expon } from 'deepbox/stats'; expon(2).mean(); // 0.5f
function f(dfn: number, dfd: number): ContinuousDistribution;F distribution.
Matches scipy.stats.f(dfn, dfd). The mean is Infinity for dfd <= 2 and the variance is Infinity for dfd <= 4 (the variable is positive, so the moments diverge rather than being undefined).
Parameters
dfnnumber- Numerator degrees of freedom, must be a finite number > 0
dfdnumber- Denominator degrees of freedom, must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfdfnordfdis not a finite number > 0
import { f } from 'deepbox/stats'; f(5, 10).ppf(0.95); // 3.325834530413012gamma
function gamma(shape: number, rate?: number): ContinuousDistribution;Gamma distribution.
Parameterized by shape and rate; SciPy's scipy.stats.gamma(a, scale=...) uses scale = 1 / rate.
Parameters
shapenumber- Shape parameter (alpha), must be a finite number > 0
rateoptionalnumber- Rate parameter (beta = 1/scale), must be a finite number > 0. Default 1.
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfshapeorrateis not a finite number > 0
import { gamma } from 'deepbox/stats'; gamma(3, 2).mean(); // 1.5, same as scipy.stats.gamma(3, scale=0.5).mean()geom
function geom(p: number): DiscreteDistribution;Geometric distribution (number of trials until first success).
P(X = k) = p * (1-p)^(k-1) for k = 1, 2, ...
Matches scipy.stats.geom(p).
Parameters
pnumber- Probability of success per trial, in (0, 1]
Returns
DiscreteDistributionDistribution object
Throws
InvalidParameterErrorIfpis not in (0, 1]
import { geom } from 'deepbox/stats'; geom(0.25).mean(); // 4hypergeom
function hypergeom(N: number, K: number, n: number): DiscreteDistribution;Hypergeometric distribution.
Models drawing n items from a population of N containing K successes, without replacement. Matches scipy.stats.hypergeom(M=N, n=K, N=n): note that SciPy names the population size M, the success count n and the number of draws N.
Parameters
Nnumber- Population size (non-negative integer)
Knumber- Number of success states in population, in [0, N]
nnumber- Number of draws, in [0, N]
Returns
DiscreteDistributionDistribution object
Throws
InvalidParameterErrorIf an argument is not an integer in its valid range
import { hypergeom } from 'deepbox/stats'; hypergeom(52, 13, 5).pmf(2); // chance of two hearts in a five-card handlaplace
function laplace(loc?: number, scale?: number): ContinuousDistribution;Laplace distribution.
Matches scipy.stats.laplace(loc, scale).
Parameters
locoptionalnumber- Location parameter (default 0)
scaleoptionalnumber- Scale parameter (default 1), must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIflocis not finite orscaleis not a finite number > 0
import { laplace } from 'deepbox/stats'; laplace(0, 2).variance(); // 8lognorm
function lognorm(mu?: number, sigma?: number): ContinuousDistribution;Lognormal distribution.
mu and sigma are the mean and standard deviation of the underlying normal distribution, so lognorm(mu, sigma) equals scipy.stats.lognorm(s=sigma, scale=exp(mu)).
Parameters
muoptionalnumber- Mean of the underlying normal distribution (default 0)
sigmaoptionalnumber- Std dev of the underlying normal distribution (default 1), must be > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfmuis not finite orsigmais not a finite number > 0
import { lognorm } from 'deepbox/stats'; lognorm(0, 1).ppf(0.5); // 1nbinom
function nbinom(r: number, p: number): DiscreteDistribution;Negative binomial distribution (number of failures before r successes).
Matches scipy.stats.nbinom(r, p). Like SciPy, r may be any positive real number (the gamma-Poisson mixture form); for an integer r it counts the failures before the r-th success.
Parameters
rnumber- Number of successes required, a finite number > 0
pnumber- Probability of success per trial, in (0, 1]
Returns
DiscreteDistributionDistribution object
Throws
InvalidParameterErrorIfris not a finite number > 0 orpis not in (0, 1]
import { nbinom } from 'deepbox/stats'; nbinom(3, 0.5).mean(); // 3norm
function norm(loc?: number, scale?: number): ContinuousDistribution;Normal (Gaussian) distribution.
Matches scipy.stats.norm(loc, scale).
Parameters
locoptionalnumber- Mean (default 0)
scaleoptionalnumber- Standard deviation (default 1), must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIflocis not finite orscaleis not a finite number > 0
import { norm } from 'deepbox/stats'; const d = norm(0, 1);d.cdf(1.96); // 0.9750021048517795d.ppf(0.975); // 1.959963984540054pareto
function pareto(alpha: number, xm?: number): ContinuousDistribution;Pareto distribution.
Matches scipy.stats.pareto(b=alpha, scale=xm).
Parameters
alphanumber- Shape parameter, must be a finite number > 0
xmoptionalnumber- Scale parameter (minimum value, default 1), must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfalphaorxmis not a finite number > 0
import { pareto } from 'deepbox/stats'; pareto(3, 1).sf(2); // 0.125poisson
function poisson(mu: number): DiscreteDistribution;Poisson distribution.
Matches scipy.stats.poisson(mu).
With mu = 0 the distribution is the point mass at 0.
Parameters
munumber- Expected number of events (rate parameter λ), must be a finite number >= 0
Returns
DiscreteDistributionDistribution object
Throws
InvalidParameterErrorIfmuis not a finite number >= 0
import { poisson } from 'deepbox/stats'; poisson(3).cdf(2); // 0.42319008112684353t
function t(df: number): ContinuousDistribution;Student's t distribution.
Matches scipy.stats.t(df). The mean is NaN for df <= 1 and the variance is Infinity for 1 < df <= 2 and NaN for df <= 1.
Parameters
dfnumber- Degrees of freedom, must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfdfis not a finite number > 0
import { t } from 'deepbox/stats'; t(10).ppf(0.975); // 2.2281388519649385uniform
function uniform(low?: number, high?: number): ContinuousDistribution;Continuous uniform distribution.
Matches scipy.stats.uniform(loc=low, scale=high - low).
Parameters
lowoptionalnumber- Lower bound (default 0)
highoptionalnumber- Upper bound (default 1), must be greater than
low
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIf the bounds are not finite orlow >= high
import { uniform } from 'deepbox/stats'; uniform(2, 6).cdf(3); // 0.25weibull
function weibull(k: number, lam?: number): ContinuousDistribution;Weibull distribution.
Matches scipy.stats.weibull_min(c=k, scale=lam).
Parameters
knumber- Shape parameter, must be a finite number > 0
lamoptionalnumber- Scale parameter (default 1), must be a finite number > 0
Returns
ContinuousDistributionDistribution object
Throws
InvalidParameterErrorIfkorlamis not a finite number > 0
import { weibull } from 'deepbox/stats'; weibull(2, 1).cdf(1); // 0.6321205588285577gaussianKde
function gaussianKde(data: number[] | Float64Array, options?: GaussianKDEOptions): GaussianKDE;Create a Gaussian kernel density estimator from data.
Details
Bandwidth is selected automatically using Scott's rule (default) or Silverman's rule, or can be specified explicitly. For one-dimensional data the bandwidth is factor * s, where s is the sample standard deviation (n - 1 denominator) and the factor is n^(-1/5) (Scott) or (3 n / 4)^(-1/5) (Silverman), as in scipy.stats.gaussian_kde. If all values are equal, s is replaced by 1.
Parameters
datanumber[] | Float64Array- 1D array of finite data points
optionsoptionalGaussianKDEOptions- KDE options (
bwMethod,weights)
Returns
GaussianKDEA GaussianKDE instance
Throws
InvalidParameterErrorIf the data are empty or contain non-finite values, the bandwidth method is invalid, or the weights are invalid
import { gaussianKde } from 'deepbox/stats'; const data = [1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5];const kde = gaussianKde(data); // Evaluate density at specific pointsconst density = kde.evaluate([1.0, 2.0, 3.0]); // Use Silverman's ruleconst kde2 = gaussianKde(data, { bwMethod: "silverman" });These older spellings still work in 1.x. New code should use the names above.
gaussian_kdePrefer gaussianKde.
import { expon, gaussianKde, meanConfidenceInterval, norm, poisson,} from "deepbox/stats"; const normal = norm(0, 1);const counts = poisson(3);const waiting = expon(2); // rate 2, so the mean is 0.5const kde = gaussianKde([1, 2, 2, 3, 4, 5], { bwMethod: "silverman" }); console.log(normal.pdf(0), normal.cdf(1.96), normal.ppf(0.975));console.log(counts.pmf(2), waiting.mean());console.log(meanConfidenceInterval([1, 2, 3, 4, 5], 0.95));console.log(kde.evaluate([2.5]));Found a mistake? Open an issue.