deepbox/random
Generation & Seeding
Global seeding with setSeed, the independent Generator class, and the basic samplers rand, randn and randint.
- Reproducibility
Overview
setSeed(n)seeds one global stream. It is shared byrand,randn,shuffle, the model initializers, dropout, tree and forest training,DataFrame.sampleand everything else that draws random numbers. The same seed gives the same numbers on every run. It does not give NumPy's or PyTorch's numbers, and 1.5.0 streams differ from 1.0.0 streams.- Without a seed, sampling uses
crypto.getRandomValues, so every run differs.clearSeed()returns to that mode. Seeded mode is not meant for cryptography. new Generator(seed)is an independent stream that ignores the global seed. It returns numbers and typed arrays (random,normalArray,uniformArray,randintArray,permutation), not tensors.randandrandnreturnfloat32tensors andrandintreturnsint32, whatever the global default dtype is. Pass{ dtype: "float64" }for double precision.getSeed()returnsundefinedwhen no seed is set, whilegetSeed()indeepbox/corereturnsnull.
Generator
Independent random number generator with its own state.
Unlike the module-level functions (which share a global seed), each Generator instance is fully independent.
import { Generator } from 'deepbox/random'; const rng1 = new Generator(42);const rng2 = new Generator(42); // Both produce identical sequencesconsole.log(rng1.random()); // same as rng2.random() // Independent from global seedimport { setSeed, rand } from 'deepbox/random';setSeed(99);// rng1 is unaffected by global seed changesMembers (17)
constructor(seed: number)Create a new Generator with a given seed.
seed: numberGet the seed used to create this Generator.
random(): numberGenerate a uniform random number in [0, 1).
randomArray(size: number): Float64ArrayGenerate an array of uniform random numbers in [0, 1).
fillNormalInto(out: Float64Array, off: number, count: number): voidFill
out[off .. off+count)with standard-normal samples (Ziggurat), drawing from this generator's own stream.fillUniformInto(out: Float64Array, off: number, count: number): voidFill
out[off .. off+count)with uniform [0,1) samples from this stream.normal(mean?: number, std?: number): numberGenerate a sample from the normal distribution (default: mean 0, std 1).
normalArray(mean?: number, std?: number, size?: number): Float64ArrayGenerate an array of normal random numbers.
uniform(low?: number, high?: number): numberGenerate a uniform random number in [low, high).
uniformArray(low?: number, high?: number, size?: number): Float64ArrayGenerate an array of uniform random numbers in [low, high).
randint(low: number, high: number): numberGenerate an unbiased random integer in [low, high).
randintArray(low: number, high: number, size: number): Int32ArrayGenerate an array of unbiased random integers in [low, high).
exponential(scale?: number): numberGenerate a sample from the exponential distribution.
bernoulli(p?: number): numberGenerate a Bernoulli trial (0 or 1).
choice(weights: ArrayLike<number>): numberRandomly select an index from weighted probabilities.
shuffle<T>(array: { [index: number]: T; readonly length: number; }): voidShuffle an array in-place using the Fisher-Yates algorithm.
permutation(n: number): Int32ArrayReturn a random permutation of integers [0, n).
setSeed
function setSeed(seed: number): void;Set global random seed.
Parameters
seednumber- Random seed value (any finite number). The seed is coerced to a uint64 internally, so the same seed always produces the same sequence.
Throws
InvalidParameterErrorWhen seed is not finite (NaN or ±Infinity)
import { setSeed, rand } from 'deepbox/random'; setSeed(42);const a = rand([5]);setSeed(42);const b = rand([5]);// a and b contain identical valuesgetSeed
function getSeed(): number | undefined;Get current random seed.
Returns
number | undefinedCurrent seed value or undefined if not set
import { setSeed, getSeed } from 'deepbox/random'; setSeed(12345);console.log(getSeed()); // 12345clearSeed
function clearSeed(): void;Clear the current random seed and revert to cryptographically secure randomness.
import { clearSeed, rand } from 'deepbox/random'; clearSeed();const x = rand([3]); // cryptographically secure randomnessrand
function rand(shape: Shape, opts?: RandomOptions): Tensor;Random values in half-open interval [0, 1).
Parameters
shapeShape- Output shape
optsoptionalRandomOptions- Options (dtype, device)
Returns
Tensor
import { rand, setSeed } from 'deepbox/random'; const x = rand([2, 3]); // 2x3 matrix of random values // Deterministic generationsetSeed(42);const a = rand([5]);setSeed(42);const b = rand([5]);// a and b are identicalrandn
function randn(shape: Shape, opts?: RandomOptions): Tensor;Random samples from standard normal distribution.
Parameters
shapeShape- Output shape
optsoptionalRandomOptions- Options (dtype, device)
Returns
Tensor
import { randn } from 'deepbox/random'; const x = randn([2, 3]); // 2x3 matrix of normal random valuesrandint
function randint(low: number, high: number, shape: Shape, opts?: RandomOptions): Tensor;Random integers in half-open interval [low, high).
Parameters
lownumber- Lowest integer (inclusive)
highnumber- Highest integer (exclusive)
shapeShape- Output shape
optsoptionalRandomOptions- Options (dtype, device)
Returns
Tensor
Throws
InvalidParameterErrorWhen low or high is not a safe integerInvalidParameterErrorWhen high <= low
import { randint } from 'deepbox/random'; const x = randint(0, 10, [5]); // 5 random integers from 0 to 9import { Generator, clearSeed, getSeed, rand, randint, randn, setSeed } from "deepbox/random"; setSeed(42);console.log(getSeed()); // 42console.log(rand([2, 2]).toString());console.log(randn([2, 2], { dtype: "float64" }).toString());console.log(randint(0, 10, [5]).toString()); const rng = new Generator(42); // independent of the global seedconsole.log(Array.from(rng.normalArray(0, 1, 3)), rng.randint(0, 10));console.log(Array.from(rng.permutation(5))); clearSeed();console.log(getSeed()); // undefinedFound a mistake? Open an issue.