public static void TestWithNoise(Vector[] inputs, double[] data) { var n = new Range(data.Length); //var kf = new SummationKernel(new ARD(new double[]{ 0 }, 0))+new WhiteNoise(); var kf = new SummationKernel(new SquaredExponential()) + new WhiteNoise(-3); var y = Variable <Vector> .Factor <double, Vector[], int[], KernelFunction>(MyFactors.GP, 1.0 /*Variable.GammaFromShapeAndRate(1,1)*/, inputs, new int[] { 0, 1 }, kf); GPFactor.settings = new Settings { solverMethod = Settings.SolverMethod.GradientDescent, }; var kf_noise = new SummationKernel(new SquaredExponential()) + new WhiteNoise(-3); var noiseFunction = Variable <Vector> .Factor <double, Vector[], int[], KernelFunction>(MyFactors.GP, 1.0 /*Variable.GammaFromShapeAndRate(1,1)*/, inputs, new int[] { 0, 1 }, kf_noise); GPFactor.settings = new Settings { solverMethod = Settings.SolverMethod.GradientDescent, }; noiseFunction.AddAttribute(new MarginalPrototype(new VectorGaussian(n.SizeAsInt))); var noiseFunctionValues = Variable.ArrayFromVector(noiseFunction, n); var noisePrecisionValues = Variable.Array <double>(n); //noisePrecisionValues[n] = Variable.Exp(noiseFunctionValues[n] + 2.0); noisePrecisionValues[n] = Variable.Exp(noiseFunctionValues[n] + Variable.GaussianFromMeanAndPrecision(0, 1)); y.AddAttribute(new MarginalPrototype(new VectorGaussian(n.SizeAsInt))); var y2noiseless = Variable.ArrayFromVector(y, n); var y2 = Variable.Array <double>(n); y2[n] = Variable.GaussianFromMeanAndPrecision(y2noiseless[n], noisePrecisionValues[n]); y2.ObservedValue = data; var ypredictiveNoiseless = Variable.ArrayFromVector(y, n); var ypredictive = Variable.Array <double>(n); ypredictive[n] = Variable.GaussianFromMeanAndPrecision(ypredictiveNoiseless[n], noisePrecisionValues[n]); var ie = new InferenceEngine(new VariationalMessagePassing()); var post = ie.Infer <Gaussian[]>(ypredictive); var mplWrapper = new MatplotlibWrapper(); mplWrapper.AddArray("x", inputs.Select(j => j[0]).ToArray()); mplWrapper.AddArray("y", data); var f = post.Select(i => i.GetMean()).ToArray(); var e = post.Select(i => 2.0 * Math.Sqrt(i.GetVariance())).ToArray(); mplWrapper.AddArray("f", f); mplWrapper.AddArray("e", e); mplWrapper.Plot(new string[] { "fill_between(x,f-e,f+e,color=\"gray\")", "plot(x,f,'k')", "scatter(x,y)" }); }
public static void Test() { var inputs = Enumerable.Range(0, 50).Select(i => Vector.Constant(1, i)).ToArray(); var data = inputs.Select(j => Math.Cos(2 * j[0] / 10.0)).ToArray(); var n = new Range(data.Length); //var kf = new SummationKernel(new ARD(new double[]{ 0 }, 0))+new WhiteNoise(); var kf = new SummationKernel(new SquaredExponential()) + new WhiteNoise(); var y = Variable <Vector> .Factor <double, Vector[], int[], KernelFunction>(MyFactors.GP, 1.0 /*Variable.GammaFromShapeAndRate(1,1)*/, inputs, new int[] { 0, 1 }, kf); GPFactor.settings = new Settings { solverMethod = Settings.SolverMethod.GradientDescent, }; y.AddAttribute(new MarginalPrototype(new VectorGaussian(n.SizeAsInt))); var y2 = Variable.ArrayFromVector(y, n); y2.ObservedValue = data; var ypredictive = Variable.ArrayFromVector(y, n); var ie = new InferenceEngine(new VariationalMessagePassing()); var post = ie.Infer <Gaussian[]>(ypredictive); var mplWrapper = new MatplotlibWrapper(); mplWrapper.AddArray("x", inputs.Select(j => j[0]).ToArray()); mplWrapper.AddArray("y", data); var f = post.Select(i => i.GetMean()).ToArray(); var e = post.Select(i => Math.Sqrt(i.GetVariance())).ToArray(); mplWrapper.AddArray("f", f); mplWrapper.AddArray("e", e); mplWrapper.Plot(new string[] { "fill_between(x,f-e,f+e,color=\"gray\")", "scatter(x,y)" }); }
/// <summary> /// Infer.NET definition of the Semi Parametric Latent Factor Model of /// Teh, Y., Seeger, M., and Jordan, M. (AISTATS 2005). /// </summary> /// <param name="inputs">Covariates X</param> /// <param name="data">Outputs Y</param> /// <param name="Q">Number of latent functions</param> /// <param name="missing">Which elements of Y are missing</param> /// <param name="nodeFunctionNoise">Whether to include node noise</param> public void SPLFM( Vector[] inputs, double[,] data, int Q, bool[,] missing = null, bool nodeFunctionNoise = false) { var toInfer = new List <IVariable>(); SummationKernel kf_node = new SummationKernel(new SquaredExponential(0)); var K_node = Utils.GramMatrix(kf_node, inputs); var D = Variable.Observed <int>(data.GetLength(0)).Named("D"); var d = new Range(D).Named("d"); var Qvar = Variable.Observed <int>(Q).Named("Q"); var q = new Range(Qvar).Named("q"); var N = Variable.Observed <int>(data.GetLength(1)).Named("N"); var n = new Range(N).Named("n"); if (missing == null) { missing = new bool[D.ObservedValue, N.ObservedValue]; // check this is all false } var ev = Variable.Bernoulli(.5).Named("ev"); var modelBlock = Variable.If(ev); var nodeSignalPrecisions = Variable.Array <double>(q).Named("nodeSignalPrecisions"); // set this to 1 if not learning signal variance var nodeSignalPrecisionsPrior = Variable.Observed(Enumerable.Range(0, Q).Select(_ => Gamma.FromShapeAndRate(.1, .1)).ToArray(), q).Named("nodeSignalPrecisionsPrior"); nodeSignalPrecisions[q] = Variable.Random <double, Gamma>(nodeSignalPrecisionsPrior[q]); var nodeFunctions = Variable.Array <Vector>(q).Named("nodeFunctions"); var K_node_inverse = Variable.Observed(K_node.Inverse()).Named("K_node_inverse"); nodeFunctions[q] = Variable <Vector> .Factor(MyFactors.VectorGaussianScaled, nodeSignalPrecisions[q], K_node_inverse); nodeFunctions.AddAttribute(new MarginalPrototype(new VectorGaussian(N.ObservedValue))); var nodeFunctionValues = Variable.Array(Variable.Array <double>(n), q).Named("nodeFunctionValues"); var nodeFunctionValuesPredictive = Variable.Array(Variable.Array <double>(n), q).Named("nodeFunctionValuesPredictive"); VariableArray <double> nodeNoisePrecisions = null; if (nodeFunctionNoise) { var nodeFunctionValuesClean = Variable.Array(Variable.Array <double>(n), q).Named("nodeFunctionValuesClean"); nodeFunctionValuesClean[q] = Variable.ArrayFromVector(nodeFunctions[q], n); nodeNoisePrecisions = Variable.Array <double>(q).Named("nodeNoisePrecisions"); var nodeNoisePrecisionPrior = Variable.Observed(Enumerable.Range(0, Q).Select(_ => Gamma.FromShapeAndRate(.1, .01)).ToArray(), q).Named("nodeNoisePrecisionPrior"); nodeNoisePrecisions[q] = Variable.Random <double, Gamma>(nodeNoisePrecisionPrior[q]); toInfer.Add(nodeNoisePrecisions); nodeFunctionValues[q][n] = Variable.GaussianFromMeanAndPrecision(nodeFunctionValuesClean[q][n], nodeNoisePrecisions[q]); nodeFunctionValuesPredictive[q][n] = Variable.GaussianFromMeanAndPrecision(nodeFunctionValuesClean[q][n], nodeNoisePrecisions[q]); } else { nodeFunctionValues[q] = Variable.ArrayFromVector(nodeFunctions[q], n); nodeFunctionValuesPredictive[q] = Variable.ArrayFromVector(nodeFunctions[q], n); } var weights = Variable.Array <double>(d, q).Named("weights"); weights[d, q] = Variable.GaussianFromMeanAndPrecision(0, 1).ForEach(d, q); var observedData = Variable.Array <double>(d, n).Named("observedData"); var noisePrecisionPrior = Variable.Observed(Gamma.FromShapeAndRate(1, .1)).Named("noisePrecisionPrior"); var noisePrecision = Variable.Random <double, Gamma>(noisePrecisionPrior).Named("noisePrecision"); var isMissing = Variable.Array <bool>(d, n).Named("isMissing"); isMissing.ObservedValue = missing; var noiseLessY = Variable.Array <double>(d, n).Named("noiseLessY"); using (Variable.ForEach(n)) using (Variable.ForEach(d)) { var temp = Variable.Array <double>(q).Named("temp"); temp[q] = weights[d, q] * nodeFunctionValues[q][n]; noiseLessY[d, n] = Variable.Sum(temp); using (Variable.IfNot(isMissing[d, n])) observedData[d, n] = Variable.GaussianFromMeanAndPrecision(noiseLessY[d, n], noisePrecision); using (Variable.If(isMissing[d, n])) observedData[d, n] = Variable.GaussianFromMeanAndPrecision(0, 1); } observedData.ObservedValue = data; var nodeFunctionsInit = Enumerable.Range(0, Q).Select(i => VectorGaussian.FromMeanAndVariance( VectorGaussian.Sample(Vector.Zero(N.ObservedValue), PositiveDefiniteMatrix.IdentityScaledBy(N.ObservedValue, 100)), PositiveDefiniteMatrix.IdentityScaledBy(N.ObservedValue, 100))).ToArray(); // should put this manually in generated code var distArray = Distribution <Vector> .Array(nodeFunctionsInit); var nodeFunctionsInitVar = Variable.Observed(distArray).Named("nodeFunctionsInitVar"); nodeFunctions.InitialiseTo(nodeFunctionsInitVar); modelBlock.CloseBlock(); toInfer.AddRange(new List <IVariable>() { ev, noiseLessY, noisePrecision, nodeFunctionValues, nodeSignalPrecisions, nodeFunctionValuesPredictive, weights }); var ie = new InferenceEngine(new VariationalMessagePassing()); ie.ModelName = "SPLFM"; var ca = ie.GetCompiledInferenceAlgorithm(toInfer.ToArray()); ca.Execute(100); var fvals = ca.Marginal <Gaussian[][]>(nodeFunctionValues.NameInGeneratedCode)[0]; // [q][n] var x = inputs.Select(i => i[0]).ToArray(); var mplWrapper = new MatplotlibWrapper(); mplWrapper.AddArray("x", x); mplWrapper.AddArray("y", fvals.Select(i => i.GetMean()).ToArray()); mplWrapper.AddArray("s", fvals.Select(i => Math.Sqrt(i.GetVariance())).ToArray()); mplWrapper.Plot(new string[] { "fill_between(x,y-s,y+s,color=\"gray\")", "ylabel(\"node (fitted)\")" }); }