Skip to content

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]) and poisson(3, [5]), and return tensors. This module only draws samples. For pdf, cdf and ppf use the distribution objects in deepbox/stats.
  • shuffle(t) shuffles in place and returns nothing. permutation(x) returns a shuffled copy, or a permutation of 0 to n-1 when x is a number. choice(a, size, replace = true, p?) samples with replacement by default, like NumPy.
  • multivariateNormal, studentT, fDistribution, gumbelSoftmax and negativeBinomial are the camelCase names. The snake_case forms are deprecated aliases.
  • Every sampler draws from the global seeded stream, so setSeed makes a run repeatable.

Functions

31

uniform

function uniform(low?: number, high?: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from continuous uniform distribution.

Parameters

lowoptional
number
Lower boundary (default: 0)
highoptional
number
Upper boundary (default: 1)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen low or high is not finite
  • InvalidParameterErrorWhen high < low
Example
import { uniform } from 'deepbox/random'; const x = uniform(-1, 1, [3, 3]);  // Values between -1 and 1

normal

function normal(mean?: number, std?: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from normal (Gaussian) distribution.

Parameters

meanoptional
number
Mean of distribution (default: 0)
stdoptional
number
Standard deviation (default: 1)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen mean or std is not finite
  • InvalidParameterErrorWhen std < 0
Example
import { normal } from 'deepbox/random'; const x = normal(0, 2, [100]);  // Mean 0, std 2

binomial

function binomial(n: number, p: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from binomial distribution.

Parameters

n
number
Number of trials (non-negative integer)
p
number
Probability of success (in [0, 1])
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen n is not finite, not an integer, or < 0
  • InvalidParameterErrorWhen p is not finite or not in [0, 1]
Example
import { binomial } from 'deepbox/random'; const x = binomial(10, 0.5, [100]);  // 10 coin flips, 100 times

poisson

function poisson(lambda: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from Poisson distribution.

Parameters

lambda
number
Expected number of events (rate, must be >= 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen lambda is not finite or < 0
Example
import { poisson } from 'deepbox/random'; const x = poisson(5, [100]);  // Rate = 5 events

exponential

function exponential(scale?: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from exponential distribution.

Parameters

scaleoptional
number
Scale parameter (1/lambda, default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen scale is not finite or <= 0
Example
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_param
number
Shape parameter (k, must be > 0)
scaleoptional
number
Scale parameter (theta, default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen shape_param is not finite or <= 0
  • InvalidParameterErrorWhen scale is not finite or <= 0
Example
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

alpha
number
Alpha parameter (must be > 0)
beta_param
number
Beta parameter (must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

Throws

  • InvalidParameterErrorWhen alpha is not finite or <= 0
  • InvalidParameterErrorWhen beta_param is not finite or <= 0
Example
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

a
Tensor | number
Input array or integer (if integer, sample from arange(a))
sizeoptional
number | Shape
Number of samples or output shape
replaceoptional
boolean
Whether to sample with replacement (default: true)
poptional
Tensor
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 false
  • InvalidParameterErrorWhen the tensor is not contiguous (non-standard strides)
  • DTypeErrorWhen input tensor has string dtype
Example
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 elements

shuffle

function shuffle(x: Tensor): void;

Randomly shuffle array in-place.

Parameters

x
Tensor
Input tensor (MODIFIED IN-PLACE)

Throws

  • InvalidParameterErrorWhen tensor is not contiguous (offset !== 0 or non-standard strides)
  • DTypeErrorWhen input tensor has string dtype
Example
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

x
Tensor | number
Input tensor or integer

Returns

Tensor

Throws

  • DTypeErrorWhen input tensor has string dtype
  • InvalidParameterErrorWhen x is a negative or non-integer number, or a non-contiguous tensor
Example
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 unchanged

multinomial

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

n
number
Number of trials (non-negative integer)
pvals
Tensor
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.
sizeoptional
number | Shape
Number of samples to draw (default: 1), or a shape of independent draws
optsoptional
RandomOptions
Options. dtype is int32, int64, float32 or float64. The default is the configured float dtype (float32 unless changed), or float64 when n exceeds 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

  • InvalidParameterErrorWhen n, pvals or size is invalid
  • DTypeErrorWhen pvals is a string tensor or dtype is unsupported
Example
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

alpha
Tensor
Concentration parameters of shape (k,), all must be positive and finite
sizeoptional
number | Shape
Number of samples (default: 1), or a shape of independent draws
optsoptional
RandomOptions
Options. dtype is 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

  • InvalidParameterErrorWhen alpha is not 1D, is empty, or has a non-positive or non-finite entry
Example
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 1

categorical

function categorical(probs: Tensor, numSamples?: number, replacement?: boolean): Tensor;

Sample from a categorical distribution.

Draws category indices with probability proportional to probs.

Parameters

probs
Tensor
1D tensor of non-negative weights (normalized internally)
numSamplesoptional
number
Number of samples to draw (default: 1)
replacementoptional
boolean
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

  • InvalidParameterErrorWhen probs is not 1D, is empty, has a negative or non-finite entry or a non-positive sum, when numSamples is 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

p
number
Probability of success (in [0, 1])
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options. dtype is int32 (default) or int64.

Returns

TensorTensor of 0s and 1s

Throws

  • InvalidParameterErrorWhen p is 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

p
number
Probability of success per trial (in (0, 1])
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options. dtype is int32 (default) or int64.

Returns

TensorTensor of positive integers

Throws

  • InvalidParameterErrorWhen p is not in (0, 1], or a sample does not fit the requested dtype (small p with int32 can exceed 2^31 - 1; use dtype: "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

meanoptional
number
Mean of underlying normal distribution (default: 0)
stdoptional
number
Std of underlying normal distribution (default: 1, must be >= 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
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

df
number
Degrees of freedom (must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of positive floats

Example
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

locoptional
number
Location parameter (default: 0)
scaleoptional
number
Scale parameter (default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of floats

Example
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

locoptional
number
Location parameter (default: 0)
scaleoptional
number
Scale parameter (default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of floats

Example
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_param
number
Shape parameter (k, must be > 0)
scaleoptional
number
Scale parameter (lambda, default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of positive floats

Example
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

left
number
Lower limit
mode
number
Mode (peak)
right
number
Upper limit
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of floats in [left, right]

Throws

  • InvalidParameterErrorWhen left >= right or mode is out of [left, right]
Example
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

ngood
number
Number of good (success) items in the population
nbad
number
Number of bad (failure) items in the population
nsample
number
Number of items drawn (without replacement)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of non-negative integers (number of good items drawn)

Throws

  • InvalidParameterErrorWhen parameters are invalid
Example
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

mu
number
Mean direction in radians
kappa
number
Concentration parameter (must be >= 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

pareto

function pareto(alpha: number, xm?: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from the Pareto (Type I) distribution.

Parameters

alpha
number
Shape parameter (must be > 0)
xmoptional
number
Scale parameter (minimum value, default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

rayleigh

function rayleigh(sigma?: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from the Rayleigh distribution.

Parameters

sigmaoptional
number
Scale parameter (default: 1, must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

Tensor

zipf

function zipf(s: number, shape?: Shape, opts?: RandomOptions): Tensor;

Random samples from the Zipf (zeta) distribution.

Parameters

s
number
Exponent parameter (must be > 1)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
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

dfn
number
Numerator degrees of freedom (must be > 0)
dfd
number
Denominator degrees of freedom (must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of positive floats

Example
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

logits
Tensor
Unnormalized log-probabilities, shape (n_categories,) or (batch, n_categories). -Infinity masks a category; NaN and +Infinity are rejected.
tauoptional
number
Temperature parameter (default: 1.0). Lower = more discrete.
hardoptional
boolean
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

  • InvalidParameterErrorWhen logits is not 1D/2D or has no categories, tau is 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

mean
Tensor
Mean vector of shape (d,)
cov
Tensor
Covariance matrix of shape (d, d); must be symmetric positive semi-definite
sizeoptional
number | Shape
Number of samples (default: 1), or a shape of independent draws
optsoptional
RandomOptions
Options. dtype is 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, size is invalid, an entry is not finite, or cov is not symmetric positive semi-definite. The check uses a relative tolerance of max(1e-8, 10 * d * eps), where eps is the machine epsilon of the dtype of cov, so covariances computed in float32 are not rejected for rounding noise.
Example
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

r
number
Number of successes (must be > 0)
p
number
Probability of success per trial (in (0, 1])
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of non-negative integers

Example
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

df
number
Degrees of freedom (must be > 0)
shapeoptional
Shape
Output shape
optsoptional
RandomOptions
Options

Returns

TensorTensor of floats

Example
import { studentT } from 'deepbox/random';const x = studentT(10, [100]);

Deprecated names

5

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.
random-distributions.ts
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());