Skip to content

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) and binom(n, p) return objects with pdf (or pmf), cdf, sf, ppf, isf, rvs, mean, variance, std and median. Continuous distributions also have entropy. rvs(size) returns a plain array.
  • Parameters follow the textbook form, which is not always SciPy's. expon(rate) and gamma(shape, rate) take a rate where SciPy takes scale = 1 / rate. lognorm(mu, sigma) takes the mean and standard deviation of the underlying normal. weibull(k, lam) and pareto(alpha, xm) take shape and scale. Each function's reference entry shows the SciPy equivalent.
  • gaussianKde(data, { bwMethod }) builds a GaussianKDE. A number passed as bwMethod is the absolute bandwidth, not SciPy's factor that multiplies the data's standard deviation. weights are supported.
  • The confidence interval functions take plain number arrays and return { lower, upper, mean, marginOfError, confidenceLevel }. meanConfidenceInterval uses the t distribution and needs at least two values. meanConfidenceIntervalZ takes a known standard deviation, proportionConfidenceInterval uses the Wald or Wilson method, and meanDiffConfidenceInterval compares two samples.
  • Special functions are accurate to about 1e-14, and the survival functions sf and isf stay accurate in the tails, where 1 - cdf(x) loses precision.

Types

5

ConfidenceInterval

interface

Result of a confidence interval computation.

  • readonly lower: number

    Lower bound of the interval

  • readonly upper: number

    Upper bound of the interval

  • readonly mean: number

    Point estimate (center)

  • readonly marginOfError: number

    Margin of error

  • readonly confidenceLevel: number

    Confidence level used

ContinuousDistribution

interface

A 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): number

    Probability density at x.

  • cdf(x: number): number

    Cumulative distribution function, P(X <= x).

  • ppf(p: number): number

    Percent point function (quantile, the inverse of cdf) for p in [0, 1].

  • sf(x: number): number

    Survival function, P(X > x), accurate in the upper tail where 1 - cdf(x) is not.

  • isf(q: number): number

    Inverse survival function: the x with sf(x) = q, for q in [0, 1].

  • rvs(size?: number): number[]

    Draws size (default 1) independent random variates.

  • mean(): number

    Expected value (NaN or Infinity where it does not exist).

  • variance(): number

    Variance (NaN or Infinity where it does not exist).

  • std(): number

    Standard deviation, the square root of variance().

  • median(): number

    Median, ppf(0.5).

  • entropy(): number

    Differential entropy in nats.

DiscreteDistribution

interface

A 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): number

    Probability mass at k.

  • cdf(x: number): number

    Cumulative distribution function, P(X <= x).

  • ppf(p: number): number

    Percent point function: the smallest integer k with cdf(k) >= p, for p in [0, 1].

  • sf(x: number): number

    Survival function, P(X > x), accurate in the upper tail where 1 - cdf(x) is not.

  • isf(q: number): number

    Inverse survival function: the smallest integer k with sf(k) <= q, for q in [0, 1].

  • rvs(size?: number): number[]

    Draws size (default 1) independent random variates.

  • mean(): number

    Expected value.

  • variance(): number

    Variance.

  • std(): number

    Standard deviation, the square root of variance().

  • median(): number

    Median, ppf(0.5).

BandwidthMethod

type

Bandwidth 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

interface

Options for gaussian_kde.

  • bwMethod?: BandwidthMethod

    Bandwidth selection method or explicit bandwidth value.

  • bw_method?: BandwidthMethoddeprecated

    Bandwidth selection method or explicit bandwidth value.

  • weights?: number[] | Float64Array

    Non-negative weights of the data points (normalized to sum to one).

Classes

1

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: Float64Array

    The fitted dataset (a copy of the input).

  • readonly nData: number

    Number of data points.

  • readonly bandwidth: number

    The bandwidth (standard deviation of the Gaussian kernel).

  • readonly weights: Float64Array | undefined

    Normalized weights of the data points, or undefined for equal weights.

  • readonly neff: number

    Effective number of data points, 1 / sum(w^2) (equal to nData without weights).

  • evaluate(points: number[] | Float64Array): Float64Array

    Evaluate the estimated density at the given points.

  • pdf(points: number[] | Float64Array): Float64Array

    Evaluate the estimated density at the given points.

  • logDensity(points: number[] | Float64Array): Float64Array

    Evaluate the log-density at the given points.

  • logpdf(points: number[] | Float64Array): Float64Array

    Evaluate the log-density at the given points.

  • integrateBox1d(low: number, high: number): number

    Integrate the estimated density over the interval [low, high].

  • integrate(): number

    Integrate the estimated density over the entire real line.

Functions

23

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

data
readonly number[]
Array of sample values (at least 2)
confidenceLeveloptional
number
Confidence level, strictly between 0 and 1 (default 0.95 for 95%)

Returns

ConfidenceIntervalConfidence interval result

Throws

  • InvalidParameterErrorIf data has fewer than 2 values or confidenceLevel is not strictly between 0 and 1
Example
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

data
readonly number[]
Array of sample values (at least 1)
popStd
number
Known population standard deviation (positive and finite)
confidenceLeveloptional
number
Confidence level, strictly between 0 and 1 (default 0.95)

Returns

ConfidenceIntervalConfidence interval result

Throws

  • InvalidParameterErrorIf data is empty, popStd is not a positive finite number, or confidenceLevel is not strictly between 0 and 1
Example
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

data1
readonly number[]
First sample (at least 2 values)
data2
readonly number[]
Second sample (at least 2 values)
confidenceLeveloptional
number
Confidence level, strictly between 0 and 1 (default 0.95)
equalVaroptional
boolean
Assume equal population variances and pool them (default false)

Returns

ConfidenceIntervalConfidence interval for (mean1 - mean2)

Throws

  • InvalidParameterErrorIf either sample has fewer than 2 values or confidenceLevel is not strictly between 0 and 1
Example
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

successes
number
Number of successes (between 0 and total)
total
number
Total number of trials (at least 1)
confidenceLeveloptional
number
Confidence level, strictly between 0 and 1 (default 0.95)
methodoptional
ProportionIntervalMethod
"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

  • InvalidParameterErrorIf total is not at least 1, successes is outside [0, total], confidenceLevel is not strictly between 0 and 1, or method is unknown
Example
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

a
number
Alpha shape parameter, must be a finite number > 0
b
number
Beta shape parameter, must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf a or b is not a finite number > 0
Example
import { beta } from 'deepbox/stats'; beta(2, 5).mean(); // 0.2857142857142857

binom

function binom(n: number, p: number): DiscreteDistribution;

Binomial distribution.

Matches scipy.stats.binom(n, p).

Parameters

n
number
Number of trials (non-negative integer)
p
number
Probability of success per trial, in [0, 1]

Returns

DiscreteDistributionDistribution object

Throws

  • InvalidParameterErrorIf n is not a non-negative integer or p is not in [0, 1]
Example
import { binom } from 'deepbox/stats'; binom(10, 0.5).pmf(5); // 0.24609375

cauchy

function cauchy(x0?: number, gammaParam?: number): ContinuousDistribution;

Cauchy distribution.

Matches scipy.stats.cauchy(loc=x0, scale=gammaParam). Mean and variance are NaN.

Parameters

x0optional
number
Location parameter (default 0)
gammaParamoptional
number
Scale parameter (default 1), must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf x0 is not finite or gammaParam is not a finite number > 0
Example
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

df
number
Degrees of freedom, must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf df is not a finite number > 0
Example
import { chi2 } from 'deepbox/stats'; chi2(3).sf(100); // upper-tail p-value, about 1.1e-21, without cancellation

expon

function expon(rate?: number): ContinuousDistribution;

Exponential distribution.

Matches scipy.stats.expon(scale=1 / rate).

Parameters

rateoptional
number
Rate parameter λ (default 1), must be a finite number > 0. Mean = 1/λ

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf rate is not a finite number > 0
Example
import { expon } from 'deepbox/stats'; expon(2).mean(); // 0.5

f

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

dfn
number
Numerator degrees of freedom, must be a finite number > 0
dfd
number
Denominator degrees of freedom, must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf dfn or dfd is not a finite number > 0
Example
import { f } from 'deepbox/stats'; f(5, 10).ppf(0.95); // 3.325834530413012

gamma

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

shape
number
Shape parameter (alpha), must be a finite number > 0
rateoptional
number
Rate parameter (beta = 1/scale), must be a finite number > 0. Default 1.

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf shape or rate is not a finite number > 0
Example
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

p
number
Probability of success per trial, in (0, 1]

Returns

DiscreteDistributionDistribution object

Throws

  • InvalidParameterErrorIf p is not in (0, 1]
Example
import { geom } from 'deepbox/stats'; geom(0.25).mean(); // 4

hypergeom

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

N
number
Population size (non-negative integer)
K
number
Number of success states in population, in [0, N]
n
number
Number of draws, in [0, N]

Returns

DiscreteDistributionDistribution object

Throws

  • InvalidParameterErrorIf an argument is not an integer in its valid range
Example
import { hypergeom } from 'deepbox/stats'; hypergeom(52, 13, 5).pmf(2); // chance of two hearts in a five-card hand

laplace

function laplace(loc?: number, scale?: number): ContinuousDistribution;

Laplace distribution.

Matches scipy.stats.laplace(loc, scale).

Parameters

locoptional
number
Location parameter (default 0)
scaleoptional
number
Scale parameter (default 1), must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf loc is not finite or scale is not a finite number > 0
Example
import { laplace } from 'deepbox/stats'; laplace(0, 2).variance(); // 8

lognorm

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

muoptional
number
Mean of the underlying normal distribution (default 0)
sigmaoptional
number
Std dev of the underlying normal distribution (default 1), must be > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf mu is not finite or sigma is not a finite number > 0
Example
import { lognorm } from 'deepbox/stats'; lognorm(0, 1).ppf(0.5); // 1

nbinom

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

r
number
Number of successes required, a finite number > 0
p
number
Probability of success per trial, in (0, 1]

Returns

DiscreteDistributionDistribution object

Throws

  • InvalidParameterErrorIf r is not a finite number > 0 or p is not in (0, 1]
Example
import { nbinom } from 'deepbox/stats'; nbinom(3, 0.5).mean(); // 3

norm

function norm(loc?: number, scale?: number): ContinuousDistribution;

Normal (Gaussian) distribution.

Matches scipy.stats.norm(loc, scale).

Parameters

locoptional
number
Mean (default 0)
scaleoptional
number
Standard deviation (default 1), must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf loc is not finite or scale is not a finite number > 0
Example
import { norm } from 'deepbox/stats'; const d = norm(0, 1);d.cdf(1.96); // 0.9750021048517795d.ppf(0.975); // 1.959963984540054

pareto

function pareto(alpha: number, xm?: number): ContinuousDistribution;

Pareto distribution.

Matches scipy.stats.pareto(b=alpha, scale=xm).

Parameters

alpha
number
Shape parameter, must be a finite number > 0
xmoptional
number
Scale parameter (minimum value, default 1), must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf alpha or xm is not a finite number > 0
Example
import { pareto } from 'deepbox/stats'; pareto(3, 1).sf(2); // 0.125

poisson

function poisson(mu: number): DiscreteDistribution;

Poisson distribution.

Matches scipy.stats.poisson(mu).

With mu = 0 the distribution is the point mass at 0.

Parameters

mu
number
Expected number of events (rate parameter λ), must be a finite number >= 0

Returns

DiscreteDistributionDistribution object

Throws

  • InvalidParameterErrorIf mu is not a finite number >= 0
Example
import { poisson } from 'deepbox/stats'; poisson(3).cdf(2); // 0.42319008112684353

t

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

df
number
Degrees of freedom, must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf df is not a finite number > 0
Example
import { t } from 'deepbox/stats'; t(10).ppf(0.975); // 2.2281388519649385

uniform

function uniform(low?: number, high?: number): ContinuousDistribution;

Continuous uniform distribution.

Matches scipy.stats.uniform(loc=low, scale=high - low).

Parameters

lowoptional
number
Lower bound (default 0)
highoptional
number
Upper bound (default 1), must be greater than low

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf the bounds are not finite or low >= high
Example
import { uniform } from 'deepbox/stats'; uniform(2, 6).cdf(3); // 0.25

weibull

function weibull(k: number, lam?: number): ContinuousDistribution;

Weibull distribution.

Matches scipy.stats.weibull_min(c=k, scale=lam).

Parameters

k
number
Shape parameter, must be a finite number > 0
lamoptional
number
Scale parameter (default 1), must be a finite number > 0

Returns

ContinuousDistributionDistribution object

Throws

  • InvalidParameterErrorIf k or lam is not a finite number > 0
Example
import { weibull } from 'deepbox/stats'; weibull(2, 1).cdf(1); // 0.6321205588285577

gaussianKde

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

data
number[] | Float64Array
1D array of finite data points
optionsoptional
GaussianKDEOptions
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
Example
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" });

Deprecated names

1

These older spellings still work in 1.x. New code should use the names above.

  • gaussian_kdePrefer gaussianKde.
stats-distributions.ts
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]));