Skip to content

Instantly share code, notes, and snippets.

@usptact
Created December 31, 2022 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usptact/0a7c5b368eaade9727ee01b5b2a8aeac to your computer and use it in GitHub Desktop.
Save usptact/0a7c5b368eaade9727ee01b5b2a8aeac to your computer and use it in GitHub Desktop.
Gaussian Density eval and comparison using Infer.NET
using Microsoft.ML.Probabilistic.Math;
using Vector = Microsoft.ML.Probabilistic.Math.Vector;
class Program
{
static void Main(string[] args)
{
Vector x = Vector.FromArray(new double[] { 0, 1 });
//Vector x = new Vector();
//Vector mean = new Vector(new double[] { 0.1, 1.1 });
Vector mean = Vector.FromArray(new double[] { 0.1, 1.1 });
PositiveDefiniteMatrix variance = new PositiveDefiniteMatrix(new double[,] { { 0.1, 0.1 }, { 0.1, 0.5 } });
int d = x.Count;
double logProb;
// evaluate the Gaussian density via direct matrix inverse and determinant.
Microsoft.ML.Probabilistic.Math.Vector dx = x - mean;
logProb = -0.5 * variance.LogDeterminant() - d * MMath.LnSqrt2PI - 0.5 * dx.Inner(variance.Inverse() * dx);
Console.WriteLine("log p(x|m,V) = {0}", logProb);
// evaluate the Gaussian density using Cholesky decomposition.
LowerTriangularMatrix varianceChol = new LowerTriangularMatrix(d, d);
varianceChol.SetToCholesky(variance);
dx.PredivideBy(varianceChol);
// new dx = inv(chol(v))*dx so that
// (new dx)'*(new dx) = dx'*inv(chol(v))'*inv(chol(v))*dx
// = dx'*inv(chol(v)*chol(v)')*dx
// = dx'*inv(v)*dx
logProb = -varianceChol.TraceLn() - d * MMath.LnSqrt2PI - 0.5 * dx.Inner(dx);
Console.WriteLine("log p(x|m,V) = {0}", logProb);
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment