Created
December 31, 2022 02:58
-
-
Save usptact/0a7c5b368eaade9727ee01b5b2a8aeac to your computer and use it in GitHub Desktop.
Gaussian Density eval and comparison using Infer.NET
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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