Public
Edited
Sep 28, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function multivariateNormal(mean, covArray) {
const n = mean.length;
const cov = math.matrix(covArray);
return {
// Probability Density Function
pdf: x => {
const c = 1 / (math.sqrt(2*math.PI)**n * math.sqrt(math.det(cov)));
return c * math.exp(
-(1/2) * math.multiply(
math.subtract(math.matrix(x), math.matrix(mean)),
math.inv(cov),
math.subtract(math.matrix(x), math.matrix(mean))
)
);
},
// Differential entropy
entropy: 0.5*math.log(math.det(cov)) + 0.5*n*(1 + math.log(2*math.PI)),
// Generate n samples using Cholesky Decomposition
sample: n_samples => Array(n_samples).fill().map(_ => {
const L = choleskyDecomposition(cov);
const z = boxMuller(n);
return math.add(
math.matrix(mean),
math.multiply(cov, math.matrix(z))
).toArray();
}),
};
}
Insert cell
// Usage example
{
const norm = multivariateNormal([0, 0], [[1, 0], [0, 2]]);
return [norm.entropy, norm.pdf([0, 0]), norm.sample(3)]
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
A = math.matrix([[1, cov12], [cov12, v2]])
Insert cell
// mean: [0, 0]
normal = multivariateNormal([0, 0], A)
Insert cell
Insert cell
samples2D = normal.sample(1000).map(d => ({x: d[0], y: d[1]}))
Insert cell
import {chart as densityChart} with {samples2D as data} from "@sw1227/fork-density-contours"
Insert cell
Insert cell
Insert cell
// Values of PDF in x: (-5, 5), y: (-5, 5)
data = d3.range(-5, 5, 0.1).map(y => (
d3.range(-5, 5, 0.1).map(x => (
normal.pdf([x, y])
))
))
Insert cell
imshow(data.reverse(), Math.min(width/100, 4), d3.interpolateViridis)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more