예제 #1
0
        public void Gamma_RightLeftNotNormalized_EachEntryMatrixIsSummedToOne()
        {
            var delta = 3;
            var numberOfStatesRightLeft = 4;
            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 11, 18), new DateTime(2011, 12, 18));
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = numberOfStatesRightLeft, Delta = delta, Emissions = CreateEmissions(observations, numberOfStatesRightLeft)
            });                                                                                                                                                                                                                                   //new HiddenMarkovModelState<NormalDistribution>(numberOfStatesRightLeft, delta, CreateEmissions(observations, numberOfStatesRightLeft)) { LogNormalized = false };

            model.Normalized = false;
            var baseParameters = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = Helper.Convert(observations), Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);
            var @params        = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = Helper.Convert(observations),
                Model        = model,
                Normalized   = model.Normalized
            };
            var estimator = new GammaEstimator <NormalDistribution>();

            for (int i = 0; i < observations.Length; i++)
            {
                Assert.AreEqual(1.0d, Math.Round(estimator.Estimate(@params)[i].Sum(), 5), string.Format("Failed Gamma Component [{1}] : {0}", estimator.Estimate(@params)[i], i));
            }
        }
예제 #2
0
        public void Sigma_ErgodicAndObservationAndLogNormalized_SigmaCalculated()
        {
            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 11, 18), new DateTime(2011, 12, 18));
            var sequence     = Helper.Convert(observations);
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = NumberOfStates, Emissions = CreateEmissions(observations, NumberOfStates)
            });                                                                                                                                                                                                  //new HiddenMarkovModelState<NormalDistribution>(NumberOfStates, CreateEmissions(observations, NumberOfStates)) { LogNormalized = true };

            model.Normalized = true;
            var baseParameters = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = sequence, Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);

            var @params = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = sequence,
                Model        = model
            };
            var gammaEstimator = new GammaEstimator <NormalDistribution>();
            var muEstimator    = new MuMultivariateEstimator <NormalDistribution>();
            var estimator      = new SigmaMultivariateEstimator <NormalDistribution>();
            var muParams       = new MuEstimationParameters <NormalDistribution>
            {
                Gamma        = gammaEstimator.Estimate(@params),
                Model        = model,
                Normalized   = model.Normalized,
                Observations = Helper.Convert(observations)
            };

            Assert.IsNotNull(estimator);
            var sigma = estimator.Estimate(new SigmaEstimationParameters <NormalDistribution, double[][]>(muParams)
            {
                Mean = muEstimator.Estimate(muParams)
            });

            for (int n = 0; n < NumberOfStates; n++)
            {
                for (int i = 0; i < sequence[0].Dimention; i++)
                {
                    for (int j = 0; j < sequence[0].Dimention; j++)
                    {
                        Assert.IsTrue(sigma[n][i, j] > 0, string.Format("Failed Sigma {0}", sigma[n][i, j]));
                    }
                }
            }
        }
        public void Estimate_KsiGammaParameters_TransitionProbabilityMatrixCalculatedAndReturned()
        {
            const int numberOfStates = 2;

            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2010, 12, 18), new DateTime(2011, 12, 18));
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = numberOfStates, Emissions = CreateEmissions(observations, numberOfStates)
            });

            model.Normalized = true;
            var observationsList = new List <IObservation>();

            for (var i = 0; i < observations.Length; i++)
            {
                observationsList.Add(new Observation(observations[i], i.ToString()));
            }
            var baseEstimator = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = Helper.Convert(observations), Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseEstimator);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseEstimator);
            var @params        = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = observationsList,
                Model        = model,
                Normalized   = model.Normalized
            };
            var gammaEstimator = new GammaEstimator <NormalDistribution>();
            var ksiEstimator   = new KsiEstimator <NormalDistribution>();
            var gamma          = gammaEstimator.Estimate(@params);
            var ksi            = ksiEstimator.Estimate(@params);
            var estimator      = new TransitionProbabilityEstimator <NormalDistribution>();
            var parameters     = new KsiGammaTransitionProbabilityMatrixParameters <NormalDistribution>
            {
                Model      = model,
                Ksi        = ksi,
                Gamma      = gamma,
                T          = observations.Length,
                Normalized = model.Normalized
            };

            var estimatedTransitionProbabilityMatrix = estimator.Estimate(parameters);

            Assert.AreEqual(1d, Math.Round(estimatedTransitionProbabilityMatrix[0][0] + estimatedTransitionProbabilityMatrix[0][1], 5));
            Assert.AreEqual(1d, Math.Round(estimatedTransitionProbabilityMatrix[1][0] + estimatedTransitionProbabilityMatrix[1][1], 5));
        }
예제 #4
0
        public void Gamma_RightLeftAndNotNormalized_GammaCalculated()
        {
            var delta = 3;
            var numberOfStatesRightLeft = 4;
            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 11, 18), new DateTime(2011, 12, 18));
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = numberOfStatesRightLeft, Delta = delta, Emissions = CreateEmissions(observations, numberOfStatesRightLeft)
            });                                                                                                                                                                                                                                   //new HiddenMarkovModelState<NormalDistribution>(numberOfStatesRightLeft, delta, CreateEmissions(observations, numberOfStatesRightLeft)) { LogNormalized = false };

            model.Normalized = false;
            var baseParameters = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = Helper.Convert(observations), Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);

            var @params = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = Helper.Convert(observations),
                Model        = model,
                Normalized   = model.Normalized
            };
            var estimator = new GammaEstimator <NormalDistribution>();

            Assert.IsNotNull(estimator);
            for (int i = 0; i < observations.Length; i++)
            {
                for (int j = 0; j < numberOfStatesRightLeft; j++)
                {
                    Assert.IsTrue(estimator.Estimate(@params)[i][j] >= 0 && estimator.Estimate(@params)[i][j] <= 1, string.Format("Failed Gamma [{1}][{2}] : {0}", estimator.Estimate(@params)[i][j], i, j));
                }
            }
        }
예제 #5
0
        public void Mu_MultivariateAndRightLeftAndNotNormalized_MuCalculated()
        {
            var delta        = 3;
            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 11, 18), new DateTime(2011, 12, 18));
            var sequence     = Helper.Convert(observations);
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = NumberOfStatesRightLeft, Delta = delta, Emissions = CreateEmissions(observations, NumberOfStatesRightLeft)
            });                                                                                                                                                                                                                                   //new HiddenMarkovModelState<NormalDistribution>(NumberOfStatesRightLeft, delta, CreateEmissions(observations, NumberOfStatesRightLeft)) { LogNormalized = false };

            model.Normalized = false;
            var baseParameters = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = sequence, Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);
            var @params        = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = sequence,
                Model        = model
            };

            var gammaEstimator = new GammaEstimator <NormalDistribution>();
            var estimator      = new MuMultivariateEstimator <NormalDistribution>();
            var muParams       = new MuEstimationParameters <NormalDistribution>
            {
                Gamma        = gammaEstimator.Estimate(@params),
                Model        = model,
                Normalized   = model.Normalized,
                Observations = sequence
            };

            Assert.IsNotNull(estimator);
            var mu = estimator.Estimate(muParams);

            for (int i = 0; i < NumberOfStatesRightLeft; i++)
            {
                for (int j = 0; j < sequence[0].Dimention; j++)
                {
                    Assert.IsTrue(mu[i][j] > 0, string.Format("Failed Mu {0}", mu[i][j]));
                }
            }
        }
예제 #6
0
        public void Gamma_ErgodicAndLogNormalized_GammaCalculated()
        {
            var util         = new TestDataUtils();
            var observations = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 11, 18), new DateTime(2011, 12, 18));
            var model        = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <NormalDistribution>()
            {
                NumberOfStates = NumberOfStates, Emissions = CreateEmissions(observations, NumberOfStates)
            });                                                                                                                                                                                                  //new HiddenMarkovModelState<NormalDistribution>(NumberOfStates) { LogNormalized = true };

            model.Normalized = true;
            var baseParameters = new BasicEstimationParameters <NormalDistribution> {
                Model = model, Observations = Helper.Convert(observations), Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <NormalDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <NormalDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);

            var @params = new AdvancedEstimationParameters <NormalDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = Helper.Convert(observations),
                Model        = model,
                Normalized   = model.Normalized
            };
            var estimator = new GammaEstimator <NormalDistribution>();

            Assert.IsNotNull(estimator);
            for (int i = 0; i < observations.Length; i++)
            {
                for (int j = 0; j < NumberOfStates; j++)
                {
                    Assert.IsTrue(estimator.Estimate(@params)[i][j] < 0, string.Format("Failed Gamma {0}", estimator.Estimate(@params)[i][j]));
                }
            }
        }
        public IHiddenMarkovModel <Mixture <IMultivariateDistribution> > Run(int maxIterations, double likelihoodTolerance)
        {
            // Initialize responce object
            var forwardBackward = new ForwardBackward(Normalized);

            do
            {
                maxIterations--;
                if (!_estimatedModel.Likelihood.EqualsTo(0))
                {
                    _currentModel = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <Mixture <IMultivariateDistribution> > {
                        Pi = _estimatedPi, TransitionProbabilityMatrix = _estimatedTransitionProbabilityMatrix, Emissions = _estimatedEmissions
                    });                                                                                                                                                                                                                                                 //new HiddenMarkovModelState<Mixture<IMultivariateDistribution>>(_estimatedPi, _estimatedTransitionProbabilityMatrix, _estimatedEmissions) { LogNormalized = _estimatedModel.LogNormalized };
                    _currentModel.Normalized = Normalized;
                    _currentModel.Likelihood = _estimatedModel.Likelihood;
                }
                // Run Forward-Backward procedure
                forwardBackward.RunForward(_observations, _currentModel);
                forwardBackward.RunBackward(_observations, _currentModel);
                // Calculate Gamma and Xi
                var @params = new MixtureSigmaEstimationParameters <Mixture <IMultivariateDistribution> >
                {
                    Alpha              = forwardBackward.Alpha,
                    Beta               = forwardBackward.Beta,
                    Observations       = _observations,
                    Model              = _currentModel,
                    Normalized         = _currentModel.Normalized,
                    L                  = _currentModel.Emission[0].Components.Length,
                    ObservationWeights = _observationWeights
                };
                _gammaEstimator = new GammaEstimator <Mixture <IMultivariateDistribution> >();
                _ksiEstimator   = new KsiEstimator <Mixture <IMultivariateDistribution> >();
                var mixtureCoefficientsEstimator = new MixtureCoefficientsEstimator <Mixture <IMultivariateDistribution> >();
                var mixtureMuEstimator           = new MixtureMuEstimator <Mixture <IMultivariateDistribution> >();    // Mean
                var mixtureSigmaEstimator        = new MixtureSigmaEstimator <Mixture <IMultivariateDistribution> >(); // Covariance
                var mixtureGammaEstimator        = new MixtureGammaEstimator <Mixture <IMultivariateDistribution> >();
                @params.Gamma           = _gammaEstimator.Estimate(@params);
                @params.GammaComponents = mixtureGammaEstimator.Estimate(@params);


                EstimatePi(_gammaEstimator.Estimate(@params));
                // TODO : weights for A
                EstimateTransitionProbabilityMatrix(_gammaEstimator.Estimate(@params), _ksiEstimator.Estimate(@params), _observationWeights, _observations.Count);

                for (var n = 0; n < _currentModel.N; n++)
                {
                    var mixturesComponents = _currentModel.Emission[n].Coefficients.Length;
                    var distributions      = new IMultivariateDistribution[mixturesComponents];
                    // Calculate coefficients for state n
                    // TODO : weights for W
                    var coefficients = mixtureCoefficientsEstimator.Estimate(@params)[n];
                    if (Normalized)
                    {
                        mixtureCoefficientsEstimator.Denormalize();
                    }
                    // TODO : weights Mu
                    @params.Mu = mixtureMuEstimator.Estimate(@params);
                    for (var l = 0; l < mixturesComponents; l++)
                    {
                        // TODO : weights Sigma
                        distributions[l] = new NormalDistribution(mixtureMuEstimator.Estimate(@params)[n, l], mixtureSigmaEstimator.Estimate(@params)[n, l]);
                    }
                    _estimatedEmissions[n] = new Mixture <IMultivariateDistribution>(coefficients, distributions);
                }
                _estimatedModel = HiddenMarkovModelStateFactory.GetState(new ModelCreationParameters <Mixture <IMultivariateDistribution> > {
                    Pi = _estimatedPi, TransitionProbabilityMatrix = _estimatedTransitionProbabilityMatrix, Emissions = _estimatedEmissions
                });
                _estimatedModel.Normalized = Normalized;
                _estimatedModel.Likelihood = forwardBackward.RunForward(_observations, _estimatedModel);
                _likelihoodDelta           = Math.Abs(Math.Abs(_currentModel.Likelihood) - Math.Abs(_estimatedModel.Likelihood));
                Debug.WriteLine("Iteration {3} , Current {0}, Estimate {1} Likelihood delta {2}", _currentModel.Likelihood, _estimatedModel.Likelihood, _likelihoodDelta, maxIterations);
            }while (_currentModel != _estimatedModel && maxIterations > 0 && _likelihoodDelta > likelihoodTolerance);

            return(_estimatedModel);
        }
예제 #8
0
        public void GammaEstimator_ABBAObservations_NotNormalizedTest()
        {
            var startDistribution = new[] { 0.85, 0.15 };
            // s = 0, t = 1
            var tpm = new double[2][];

            tpm[0] = new[] { 0.3, 0.7 };
            tpm[1] = new[] { 0.1, 0.9 };

            var observations = new List <IObservation>
            {
                new Observation(new double[] { 0 }, "A"),
                new Observation(new double[] { 1 }, "B"),
                new Observation(new double[] { 1 }, "B"),
                new Observation(new double[] { 0 }, "A")
            };

            var emissions = new DiscreteDistribution[2];

            emissions[0] = new DiscreteDistribution(new double[] { 0, 1 }, new[] { 0.4, 0.6 });
            emissions[1] = new DiscreteDistribution(new double[] { 0, 1 }, new[] { 0.5, 0.5 });

            var model = HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <DiscreteDistribution>()
            {
                Pi = startDistribution, TransitionProbabilityMatrix = tpm, Emissions = emissions
            });                                                                                                                                                                                     //new HiddenMarkovModel(startDistribution, tpm, emissions) { LogNormalized = false };

            model.Normalized = false;
            var baseParameters = new BasicEstimationParameters <DiscreteDistribution> {
                Model = model, Observations = observations, Normalized = model.Normalized
            };
            var alphaEstimator = new AlphaEstimator <DiscreteDistribution>();
            var alpha          = alphaEstimator.Estimate(baseParameters);
            var betaEstimator  = new BetaEstimator <DiscreteDistribution>();
            var beta           = betaEstimator.Estimate(baseParameters);

            var @params = new AdvancedEstimationParameters <DiscreteDistribution>
            {
                Alpha        = alpha,
                Beta         = beta,
                Observations = observations,
                Model        = model
            };
            var gammaEstimator = new GammaEstimator <DiscreteDistribution>();
            var gamma          = gammaEstimator.Estimate(@params);

            Assert.AreEqual(0.8258482510939813, gamma[0][0]);
            Assert.AreEqual(0.17415174890601867, gamma[0][1]);
            Assert.AreEqual(1d, gamma[0].Sum());

            Assert.AreEqual(0.3069572858154187, gamma[1][0]);
            Assert.AreEqual(0.69304271418458141, gamma[1][1]);
            Assert.AreEqual(1d, gamma[1].Sum());

            Assert.AreEqual(0.17998403530294202, gamma[2][0]);
            Assert.AreEqual(0.82001596469705806, gamma[2][1]);
            Assert.AreEqual(1d, gamma[2].Sum());

            Assert.AreEqual(0.112893449466425, gamma[3][0]);
            Assert.AreEqual(0.887106550533575, gamma[3][1]);
            Assert.AreEqual(1d, gamma[2].Sum());
        }