Tutorial 2: Truncated GaussianIn the previous tutorial, you saw how to create random variables and infer their values. This tutorial shows how to change values in a model in a way that avoids unnecessary recompilation and signifiantly improves efficiency.
You can run the code in this tutorial either using the Examples Browser or by opening the Tutorials solution in Visual Studio and executing TruncatedGaussian.cs and TruncatedGaussianEfficient.cs.
Clipping that GaussianIn this example, we look at how to create a variable with a truncated or clipped Gaussian distribution. This plot shows the type of distribution we are trying to create:
The blue line shows a Gaussian distribution with mean zero and variance one. The shaded area is the Gaussian distribution truncated at x=0.5.
We can achieve this using what we learned in the previous tutorial, by creating a random double variable with a Gaussian prior but now we also need to add a constraint constraining it to be greater than 0.5. This can be achieved with the following code:
which is the moment-matched Gaussian distribution. To check this, you can run the Matlab code: Doing it again, and again...Suppose we want to investigate what happens when we changed the truncation threshold to values other than 0.5. The simplest way to do this is to place all of the above code in a loop:
This is the correct answer but if you run this code you will notice a small delay before each line is printed out. This is because the model is being re-compiled on every run through the loop - for details read about how Infer.NET works. We can make this code much more efficient by making the threshold a Variable and changing its observed value. Observed values can be modified after the model has been compiled, so that changes in their values can be incorporated quickly without any overhead cost. To create a variable for the threshold, we write:
It is normal to provide a name for the variable, which should be the name of the variable in your code. You can now use this variable directly in the constraint expression:
Notice that we have not yet set the value of threshold. If we tried to infer x at this point, we would get an exception with the message "Variable 'threshold' has no definition". To set the value of a variable, we set its ObservedValue property. In this case, we set the value inside the loop and then call Infer(x):
When this code is executed, it gives the same output as above but much more quickly. Try running each version in the Examples Browser, with Show Timings checked, and compare the speed - on my machine the total time went from 1.5s to 150ms, a tenfold speed-up. The general rule is:
|


