Infer.NET user guide : Tutorials and examples

How to save distributions to disk

The Infer.NET distribution classes such as Bernoulli and Gaussian are all marked Serializable and can be serialized by the standard .NET serialization mechanisms. These mechanisms are reviewed below.

Binary format

The simplest and most efficient way to serialize data to disk is in binary format, using the class System.Runtime.Serialization.Formatters.Binary.BinaryFormatter. Here is an example of saving and loading a Dirichlet distribution:

Dirichlet d = new Dirichlet(3.0, 1.0, 2.0);
BinaryFormatter serializer = new BinaryFormatter();
// write to disk
using (FileStream stream = new FileStream("temp.bin", FileMode.Create)) {
 
serializer.Serialize(stream, d);
}
// read from disk
using (FileStream stream = new FileStream("temp.bin", FileMode.Open)) {
 
Dirichlet d2 = (Dirichlet)serializer.Deserialize(stream);
 
Console.WriteLine(d2);
}

XML format

Another option is to save in XML format, using the class System.Runtime.Serialization.DataContractSerializer. Because some distributions require custom XML serialization, you need to pass in an Infer.NET DataContractSurrogate when creating the serializer. Here is an example:

Dirichlet d = new Dirichlet(3.0, 1.0, 2.0);
DataContractSerializer serializer = new DataContractSerializer(typeof(Dirichlet), null, Int16.MaxValue, false, true, new DataContractSurrogate());
// write to disk
using (FileStream stream = new FileStream("temp.xml", FileMode.Create)) {
  XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
 
serializer.WriteObject(writer, d);
}
// read from disk 
using (FileStream stream = new FileStream("temp.xml", FileMode.Open)) { 
 
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
 
Dirichlet d2 = (Dirichlet)serializer.ReadObject(reader);
  Console.WriteLine(d2);
}

Note that DataContractSerializer is preferable to the older XmlSerializer class.

©2009-2014 Microsoft Corporation. All rights reserved.  Terms of Use | Trademarks | Privacy Statement