Example 21
beginner
21
Random
Distributions
Sampling

Random Sampling & Distributions

Random number generation is essential for weight initialization, data augmentation, Monte Carlo simulation, and stochastic algorithms. This example demonstrates all Deepbox random functions: setSeed/getSeed/clearSeed for reproducibility, rand/randn for quick uniform/normal tensors, uniform/normal for parametric distributions, binomial/poisson/exponential/gamma/beta for specialized distributions, randint for random integers, choice for sampling from a tensor, shuffle for in-place randomization, and permutation for shuffled copies. Each function is called with explicit shapes and the output is printed so you can see the distribution characteristics.

Deepbox Modules Used

deepbox/random

What You Will Learn

  • setSeed(42) makes all subsequent random calls deterministic
  • rand/randn are shortcuts for uniform [0,1) and standard normal
  • Use binomial/poisson/exponential/gamma/beta for specialized distributions
  • choice samples from a tensor; permutation returns a shuffled copy
  • clearSeed returns to non-deterministic mode

Source Code

21-random-sampling/index.ts
1import {2  setSeed, getSeed, clearSeed,3  rand, randn, uniform, normal, binomial, poisson,4  randint, choice, shuffle, permutation5} from "deepbox/random";6import { tensor } from "deepbox/ndarray";78setSeed(42);9console.log("Seed:", getSeed());  // 421011// Quick random tensors12console.log("rand [2,3]:", rand([2, 3]).toString());13console.log("randn [5]:", randn([5]).toString());1415// Parametric distributions16console.log("\nuniform(0,10,[3]):", uniform(0, 10, [3]).toString());17console.log("normal(5,2,[3]):", normal(5, 2, [3]).toString());18console.log("binomial(10,0.5,[5]):", binomial(10, 0.5, [5]).toString());19console.log("poisson(3,[5]):", poisson(3, [5]).toString());20console.log("randint(0,10,[5]):", randint(0, 10, [5]).toString());2122// Sampling23const data = tensor([10, 20, 30, 40, 50]);24console.log("\nchoice(5, size=3):", choice(data, 3).toString());25console.log("permutation(5):", permutation(5).toString());2627clearSeed();28console.log("\nSeed after clear:", getSeed());  // undefined

Console Output

$ npx tsx 21-random-sampling/index.ts
Seed: 42
rand [2,3]: [[0.374, 0.951, 0.732], [0.598, 0.156, 0.156]]
randn [5]: [-0.531, 0.293, -1.175, 0.862, -0.213]

uniform(0,10,[3]): [3.74, 9.51, 7.32]
normal(5,2,[3]): [3.94, 5.59, 2.65]
binomial(10,0.5,[5]): [5, 6, 4, 7, 3]
poisson(3,[5]): [2, 4, 3, 1, 5]
randint(0,10,[5]): [3, 9, 7, 5, 1]

choice(5, size=3): [30, 10, 50]
permutation(5): [3, 0, 4, 1, 2]

Seed after clear: undefined