public void LearnTest4()
{
// Create a Continuous density Hidden Markov Model Sequence Classifier
// to detect a multivariate sequence and the same sequence backwards.
double[][][] sequences = new double[][][]
{
new double[][]
{
// This is the first sequence with label = 0
new double[] { 0 },
new double[] { 1 },
new double[] { 2 },
new double[] { 3 },
new double[] { 4 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 4 },
new double[] { 3 },
new double[] { 2 },
new double[] { 1 },
new double[] { 0 },
}
};
// Labels for the sequences
int[] labels = { 0, 1 };
// Create a mixture of two 1-dimensional normal distributions (by default,
// initialized with zero mean and unit covariance matrices).
var density = new MultivariateMixture<MultivariateNormalDistribution>(
new MultivariateNormalDistribution(1),
new MultivariateNormalDistribution(1));
// Creates a sequence classifier containing 2 hidden Markov Models with 2 states
// and an underlying multivariate mixture of Normal distributions as density.
var classifier = new HiddenMarkovClassifier<MultivariateMixture<MultivariateNormalDistribution>, double[]>(
2, new Ergodic(2), density);
// Configure the learning algorithms to train the sequence classifier
var teacher = new HiddenMarkovClassifierLearning<MultivariateMixture<MultivariateNormalDistribution>, double[]>(classifier)
{
// Train each model until the log-likelihood changes less than 0.0001
Learner = modelIndex => new BaumWelchLearning<MultivariateMixture<MultivariateNormalDistribution>, double[]>(classifier.Models[modelIndex])
{
Tolerance = 0.0001,
Iterations = 0,
}
};
// Train the sequence classifier using the algorithm
teacher.Learn(sequences, labels);
double logLikelihood = teacher.LogLikelihood;
// Calculate the probability that the given
// sequences originated from the model
double likelihood1, likelihood2;
int c1, c2;
// Try to classify the 1st sequence (output should be 0)
likelihood1 = classifier.Probability(sequences[0], out c1);
// Try to classify the 2nd sequence (output should be 1)
likelihood2 = classifier.Probability(sequences[1], out c2);
Assert.AreEqual(0, c1);
Assert.AreEqual(1, c2);
Assert.AreEqual(-13.271981026832933, logLikelihood, 1e-10);
Assert.AreEqual(0.99999791320102149, likelihood1, 1e-10);
Assert.AreEqual(0.99999791320102149, likelihood2, 1e-10);
}