deepbox/random
Distributions & Sampling
Samplers for continuous and discrete distributions, categorical and multivariate draws, and shuffling and selection helpers.
- Sampling
Overview
- Samplers take the distribution parameters first and the output shape last, as in
normal(0, 1, [3])andpoisson(3, [5]), and return tensors. This module only draws samples. Forpdf,cdfandppfuse the distribution objects indeepbox/stats. shuffle(t)shuffles in place and returns nothing.permutation(x)returns a shuffled copy, or a permutation of 0 to n-1 whenxis a number.choice(a, size, replace = true, p?)samples with replacement by default, like NumPy.multivariateNormal,studentT,fDistribution,gumbelSoftmaxandnegativeBinomialare the camelCase names. The snake_case forms are deprecated aliases.- Every sampler draws from the global seeded stream, so
setSeedmakes a run repeatable.
uniform
function uniform(low?: number, high?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from continuous uniform distribution.
Parameters
lowoptionalnumber- Lower boundary (default: 0)
highoptionalnumber- Upper boundary (default: 1)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen low or high is not finiteInvalidParameterErrorWhen high < low
import { uniform } from 'deepbox/random'; const x = uniform(-1, 1, [3, 3]); // Values between -1 and 1normal
function normal(mean?: number, std?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from normal (Gaussian) distribution.
Parameters
meanoptionalnumber- Mean of distribution (default: 0)
stdoptionalnumber- Standard deviation (default: 1)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen mean or std is not finiteInvalidParameterErrorWhen std < 0
import { normal } from 'deepbox/random'; const x = normal(0, 2, [100]); // Mean 0, std 2binomial
function binomial(n: number, p: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from binomial distribution.
Parameters
nnumber- Number of trials (non-negative integer)
pnumber- Probability of success (in [0, 1])
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen n is not finite, not an integer, or < 0InvalidParameterErrorWhen p is not finite or not in [0, 1]
import { binomial } from 'deepbox/random'; const x = binomial(10, 0.5, [100]); // 10 coin flips, 100 timespoisson
function poisson(lambda: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Poisson distribution.
Parameters
lambdanumber- Expected number of events (rate, must be >= 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen lambda is not finite or < 0
import { poisson } from 'deepbox/random'; const x = poisson(5, [100]); // Rate = 5 eventsexponential
function exponential(scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from exponential distribution.
Parameters
scaleoptionalnumber- Scale parameter (1/lambda, default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen scale is not finite or <= 0
import { exponential } from 'deepbox/random'; const x = exponential(2, [100]);gamma
function gamma(shape_param: number, scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from gamma distribution.
Parameters
shape_paramnumber- Shape parameter (k, must be > 0)
scaleoptionalnumber- Scale parameter (theta, default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen shape_param is not finite or <= 0InvalidParameterErrorWhen scale is not finite or <= 0
import { gamma } from 'deepbox/random'; const x = gamma(2, 2, [100]);beta
function beta(alpha: number, beta_param: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from beta distribution.
Parameters
alphanumber- Alpha parameter (must be > 0)
beta_paramnumber- Beta parameter (must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
Throws
InvalidParameterErrorWhen alpha is not finite or <= 0InvalidParameterErrorWhen beta_param is not finite or <= 0
import { beta } from 'deepbox/random'; const x = beta(2, 5, [100]);choice
function choice(a: Tensor | number, size?: number | Shape, replace?: boolean, p?: Tensor): Tensor;Random sample from array.
Parameters
aTensor | number- Input array or integer (if integer, sample from arange(a))
sizeoptionalnumber | Shape- Number of samples or output shape
replaceoptionalboolean- Whether to sample with replacement (default: true)
poptionalTensor- Optional probability weights for weighted sampling
Returns
Tensor
Throws
InvalidParameterErrorWhen population size is invalid (not finite, not integer, or < 0)InvalidParameterErrorWhen size > population and replace is falseInvalidParameterErrorWhen the tensor is not contiguous (non-standard strides)DTypeErrorWhen input tensor has string dtype
import { choice, tensor } from 'deepbox/random'; const x = tensor([1, 2, 3, 4, 5]);const sample = choice(x, 3); // Pick 3 elements with replacement // Without replacementconst unique = choice(x, 3, false); // All different elementsshuffle
function shuffle(x: Tensor): void;Randomly shuffle array in-place.
Parameters
xTensor- Input tensor (MODIFIED IN-PLACE)
Throws
InvalidParameterErrorWhen tensor is not contiguous (offset !== 0 or non-standard strides)DTypeErrorWhen input tensor has string dtype
import { shuffle, tensor } from 'deepbox/random'; const x = tensor([1, 2, 3, 4, 5]);shuffle(x); // x is now shuffled IN-PLACEconsole.log(x); // e.g., [3, 1, 5, 2, 4]permutation
function permutation(x: Tensor | number): Tensor;Return random permutation of array.
Parameters
xTensor | number- Input tensor or integer
Returns
Tensor
Throws
DTypeErrorWhen input tensor has string dtypeInvalidParameterErrorWhen x is a negative or non-integer number, or a non-contiguous tensor
import { permutation, tensor } from 'deepbox/random'; // Permutation of integersconst x = permutation(10); // Random permutation of [0...9] // Permutation of tensor (does not modify original)const original = tensor([1, 2, 3, 4, 5]);const shuffled = permutation(original);// original is unchangedmultinomial
function multinomial(n: number, pvals: Tensor, size?: number | Shape, opts?: RandomOptions): Tensor;Draw samples from a multinomial distribution.
Counts are generated with a chain of conditional binomial draws (one per category), so the cost does not grow with the number of trials n.
Parameters
nnumber- Number of trials (non-negative integer)
pvalsTensor- Probabilities of each outcome, 1D tensor of shape (k,). Entries must be finite and non-negative with a positive sum; they are normalized by their sum.
sizeoptionalnumber | Shape- Number of samples to draw (default: 1), or a shape of independent draws
optsoptionalRandomOptions- Options.
dtypeis int32, int64, float32 or float64. The default is the configured float dtype (float32 unless changed), or float64 whennexceeds 2^24 so that every count is exact.
Returns
TensorTensor of shape (size, k), or (...size, k) when size is a shape, holding the count of each outcome. Every row sums to n.
Throws
InvalidParameterErrorWhenn,pvalsorsizeis invalidDTypeErrorWhenpvalsis a string tensor ordtypeis unsupported
import { multinomial } from 'deepbox/random';import { tensor } from 'deepbox/ndarray'; const probs = tensor([0.2, 0.5, 0.3]);const samples = multinomial(10, probs, 5); // shape [5, 3]dirichlet
function dirichlet(alpha: Tensor, size?: number | Shape, opts?: RandomOptions): Tensor;Draw samples from a Dirichlet distribution.
Each row is a vector of independent Gamma(alpha_i, 1) draws divided by their sum. When any concentration is below 1 the draws are combined in log space, so very small concentrations give near one-hot rows instead of failing.
Parameters
alphaTensor- Concentration parameters of shape (k,), all must be positive and finite
sizeoptionalnumber | Shape- Number of samples (default: 1), or a shape of independent draws
optsoptionalRandomOptions- Options.
dtypeis float32 or float64 (default: the configured default dtype).
Returns
TensorTensor of shape (size, k), or (...size, k) when size is a shape; each row sums to 1
Throws
InvalidParameterErrorWhenalphais not 1D, is empty, or has a non-positive or non-finite entry
import { dirichlet } from 'deepbox/random';import { tensor } from 'deepbox/ndarray'; const alpha = tensor([1, 1, 1]);const samples = dirichlet(alpha, 5); // shape [5, 3], each row sums to 1categorical
function categorical(probs: Tensor, numSamples?: number, replacement?: boolean): Tensor;Sample from a categorical distribution.
Draws category indices with probability proportional to probs.
Parameters
probsTensor- 1D tensor of non-negative weights (normalized internally)
numSamplesoptionalnumber- Number of samples to draw (default: 1)
replacementoptionalboolean- Whether to sample with replacement (default: true). Without replacement each draw is proportional to the weight of the categories not yet drawn.
Returns
Tensor1D int32 tensor of sampled indices
Throws
InvalidParameterErrorWhenprobsis not 1D, is empty, has a negative or non-finite entry or a non-positive sum, whennumSamplesis not a positive integer, or when sampling without replacement needs more categories than have non-zero probability
bernoulli
function bernoulli(p: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Bernoulli distribution.
Parameters
pnumber- Probability of success (in [0, 1])
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options.
dtypeis int32 (default) or int64.
Returns
TensorTensor of 0s and 1s
Throws
InvalidParameterErrorWhenpis not a finite number in [0, 1]
geometric
function geometric(p: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from geometric distribution.
Number of Bernoulli trials needed to get one success. P(X=k) = (1-p)^(k-1) * p, k=1,2,...
Parameters
pnumber- Probability of success per trial (in (0, 1])
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options.
dtypeis int32 (default) or int64.
Returns
TensorTensor of positive integers
Throws
InvalidParameterErrorWhenpis not in (0, 1], or a sample does not fit the requested dtype (smallpwith int32 can exceed 2^31 - 1; usedtype: "int64")
lognormal
function lognormal(mean?: number, std?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from log-normal distribution.
If X ~ Normal(mean, std), then exp(X) ~ LogNormal(mean, std).
Parameters
meanoptionalnumber- Mean of underlying normal distribution (default: 0)
stdoptionalnumber- Std of underlying normal distribution (default: 1, must be >= 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of positive floats
chi2
function chi2(df: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from chi-squared distribution.
Chi-squared with k degrees of freedom is Gamma(k/2, 2).
Parameters
dfnumber- Degrees of freedom (must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of positive floats
import { chi2 } from 'deepbox/random';const x = chi2(5, [100]);laplace
function laplace(loc?: number, scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Laplace distribution.
Uses inverse CDF: loc + scale * ln(2U) for U < 1/2, loc - scale * ln(2(1 - U)) otherwise.
Parameters
locoptionalnumber- Location parameter (default: 0)
scaleoptionalnumber- Scale parameter (default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of floats
import { laplace } from 'deepbox/random';const x = laplace(0, 1, [100]);cauchy
function cauchy(loc?: number, scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Cauchy distribution.
Uses inverse CDF: loc + scale * tan(π * (U - 0.5))
Parameters
locoptionalnumber- Location parameter (default: 0)
scaleoptionalnumber- Scale parameter (default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of floats
import { cauchy } from 'deepbox/random';const x = cauchy(0, 1, [100]);weibull
function weibull(shape_param: number, scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Weibull distribution.
Uses inverse CDF: scale * (-ln(U))^(1/shape_param)
Parameters
shape_paramnumber- Shape parameter (k, must be > 0)
scaleoptionalnumber- Scale parameter (lambda, default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of positive floats
import { weibull } from 'deepbox/random';const x = weibull(1.5, 1, [100]);triangular
function triangular(left: number, mode: number, right: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from triangular distribution.
Parameters
leftnumber- Lower limit
modenumber- Mode (peak)
rightnumber- Upper limit
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of floats in [left, right]
Throws
InvalidParameterErrorWhen left >= right or mode is out of [left, right]
import { triangular } from 'deepbox/random';const x = triangular(0, 0.5, 1, [100]);hypergeometric
function hypergeometric(ngood: number, nbad: number, nsample: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from hypergeometric distribution.
Models drawing without replacement from a finite population.
Parameters
ngoodnumber- Number of good (success) items in the population
nbadnumber- Number of bad (failure) items in the population
nsamplenumber- Number of items drawn (without replacement)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of non-negative integers (number of good items drawn)
Throws
InvalidParameterErrorWhen parameters are invalid
import { hypergeometric } from 'deepbox/random';const x = hypergeometric(10, 5, 7, [100]);vonmises
function vonmises(mu: number, kappa: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from the von Mises distribution (circular normal).
Parameters
munumber- Mean direction in radians
kappanumber- Concentration parameter (must be >= 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
pareto
function pareto(alpha: number, xm?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from the Pareto (Type I) distribution.
Parameters
alphanumber- Shape parameter (must be > 0)
xmoptionalnumber- Scale parameter (minimum value, default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
rayleigh
function rayleigh(sigma?: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from the Rayleigh distribution.
Parameters
sigmaoptionalnumber- Scale parameter (default: 1, must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
zipf
function zipf(s: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from the Zipf (zeta) distribution.
Parameters
snumber- Exponent parameter (must be > 1)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
Tensor
fDistribution
function fDistribution(dfn: number, dfd: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from F distribution.
If X1 ~ Chi2(dfn) and X2 ~ Chi2(dfd), then (X1/dfn) / (X2/dfd) ~ F(dfn, dfd).
Parameters
dfnnumber- Numerator degrees of freedom (must be > 0)
dfdnumber- Denominator degrees of freedom (must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of positive floats
import { fDistribution } from 'deepbox/random';const x = fDistribution(5, 10, [100]);gumbelSoftmax
function gumbelSoftmax(logits: Tensor, tau?: number, hard?: boolean): Tensor;Sample from a categorical distribution using the Gumbel-Softmax trick.
Adds Gumbel(0, 1) noise to the logits and applies a temperature softmax, giving approximate one-hot samples. The result is a plain tensor: no gradient flows through it.
Parameters
logitsTensor- Unnormalized log-probabilities, shape (n_categories,) or (batch, n_categories).
-Infinitymasks a category; NaN and+Infinityare rejected. tauoptionalnumber- Temperature parameter (default: 1.0). Lower = more discrete.
hardoptionalboolean- If true, returns hard one-hot vectors (default: false)
Returns
Tensorfloat64 tensor of the same shape as logits with softmax probabilities (or one-hot rows)
Throws
InvalidParameterErrorWhenlogitsis not 1D/2D or has no categories,tauis not a positive finite number, a logit is NaN or+Infinity, or a row has no finite logit
multivariateNormal
function multivariateNormal(mean: Tensor, cov: Tensor, size?: number | Shape, opts?: RandomOptions): Tensor;Draw samples from a multivariate normal distribution.
Uses the Cholesky factor of the covariance matrix: x = mean + L z with z ~ N(0, I). Singular (rank-deficient) covariances are supported.
Parameters
meanTensor- Mean vector of shape (d,)
covTensor- Covariance matrix of shape (d, d); must be symmetric positive semi-definite
sizeoptionalnumber | Shape- Number of samples (default: 1), or a shape of independent draws
optsoptionalRandomOptions- Options.
dtypeis float32 or float64 (default: the configured default dtype).
Returns
TensorTensor of shape (size, d), or (...size, d) when size is a shape
Throws
InvalidParameterErrorWhen shapes do not match,sizeis invalid, an entry is not finite, orcovis not symmetric positive semi-definite. The check uses a relative tolerance ofmax(1e-8, 10 * d * eps), whereepsis the machine epsilon of the dtype ofcov, so covariances computed in float32 are not rejected for rounding noise.
import { multivariateNormal } from 'deepbox/random';import { tensor } from 'deepbox/ndarray'; const mean = tensor([0, 0]);const cov = tensor([[1, 0.5], [0.5, 1]]);const samples = multivariateNormal(mean, cov, 100); // shape [100, 2]negativeBinomial
function negativeBinomial(r: number, p: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from negative binomial distribution.
Number of failures before achieving r successes. Uses gamma-Poisson mixture: sample lambda ~ Gamma(r, (1-p)/p), then X ~ Poisson(lambda).
Parameters
rnumber- Number of successes (must be > 0)
pnumber- Probability of success per trial (in (0, 1])
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of non-negative integers
import { negativeBinomial } from 'deepbox/random';const x = negativeBinomial(5, 0.5, [100]);studentT
function studentT(df: number, shape?: Shape, opts?: RandomOptions): Tensor;Random samples from Student's t distribution.
If Z ~ N(0,1) and V ~ Chi2(df), then Z / sqrt(V/df) ~ t(df).
Parameters
dfnumber- Degrees of freedom (must be > 0)
shapeoptionalShape- Output shape
optsoptionalRandomOptions- Options
Returns
TensorTensor of floats
import { studentT } from 'deepbox/random';const x = studentT(10, [100]);These older spellings still work in 1.x. New code should use the names above.
multivariate_normalPrefer multivariateNormal.gumbel_softmaxPrefer gumbelSoftmax.student_tPrefer studentT.f_distributionPrefer fDistribution.negative_binomialPrefer negativeBinomial.
import { tensor } from "deepbox/ndarray";import { beta, choice, dirichlet, multivariateNormal, normal, permutation, poisson, setSeed, shuffle, uniform,} from "deepbox/random"; setSeed(7);console.log(uniform(-1, 1, [3]).toString());console.log(normal(0, 1, [3]).toString());console.log(poisson(3, [5]).toString());console.log(beta(2, 5, [5]).toString());console.log(choice(tensor([10, 20, 30]), 2, false).toString()); // without replacementconsole.log(permutation(5).toString());console.log(dirichlet(tensor([1, 1, 1]), 2).toString());console.log(multivariateNormal(tensor([0, 0]), tensor([[1, 0.5], [0.5, 1]]), 3).shape); const items = tensor([1, 2, 3, 4]);shuffle(items); // in placeconsole.log(items.toString());Found a mistake? Open an issue.