Exemple #1
0
        public void Ksi_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 = true };

            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 KsiEstimator <NormalDistribution>();

            for (int t = 0; t < observations.Length - 1; t++)
            {
                Assert.AreEqual(1.0d, Math.Round(estimator.Estimate(@params)[t].Sum(), 5), string.Format("Failed Ksi [{1}] :{0}", new Matrix(estimator.Estimate(@params)[t]), t));
            }
        }
        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));
        }
Exemple #3
0
        public void Ksi_RightLeftAndNotNormalized_KsiCalculated()
        {
            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 = true };

            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 KsiEstimator <NormalDistribution>();

            Assert.IsNotNull(estimator);
            for (int t = 0; t < observations.Length - 1; t++)
            {
                for (int i = 0; i < numberOfStatesRightLeft; i++)
                {
                    for (int j = 0; j < numberOfStatesRightLeft; j++)
                    {
                        Assert.IsTrue(estimator.Estimate(@params)[t][i, j] >= 0 && estimator.Estimate(@params)[t][i, j] < 1, string.Format("Failed Ksi [{1}][{2},{3}]:{0}", estimator.Estimate(@params)[t][i, j], t, i, j));
                    }
                }
            }
        }
Exemple #4
0
        public void Ksi_ErgodicAndLogNormalized_KsiCalculated()
        {
            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, CreateEmissions(observations, 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 KsiEstimator <NormalDistribution>();

            Assert.IsNotNull(estimator);
            for (int t = 0; t < observations.Length - 1; t++)
            {
                for (int i = 0; i < NumberOfStates; i++)
                {
                    for (int j = 0; j < NumberOfStates; j++)
                    {
                        Assert.IsTrue(estimator.Estimate(@params)[t][i, j] < 0, string.Format("Failed Ksi {0}", estimator.Estimate(@params)[t][i, j]));
                    }
                }
            }
        }
Exemple #5
0
        public void KsiEstimator_Parameters_KsiEstimatorCreated()
        {
            var estimator = new KsiEstimator <NormalDistribution>();

            Assert.IsNotNull(estimator);
        }
        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);
        }
        public void KsiEstimator_ABBAObservation_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,
                Normalized   = model.Normalized
            };

            var ksiEstimator = new KsiEstimator <DiscreteDistribution>();
            var ksi          = ksiEstimator.Estimate(@params);

            Assert.AreEqual(0.28593281418422561, ksi[0][0, 0]);
            Assert.AreEqual(0.53991543690975563, ksi[0][0, 1]);
            Assert.AreEqual(0.021024471631193059, ksi[0][1, 0]);
            Assert.AreEqual(0.15312727727482567, ksi[0][1, 1]);
            Assert.AreEqual(1d, ksi[0].Sum());

            Assert.AreEqual(0.10140018110107153, ksi[1][0, 0]);
            Assert.AreEqual(0.20555710471434716, ksi[1][0, 1]);
            Assert.AreEqual(0.0785838542018705, ksi[1][1, 0]);
            Assert.AreEqual(0.61445885998271088, ksi[1][1, 1]);
            Assert.AreEqual(1d, ksi[1].Sum());

            Assert.AreEqual(0.045953370715644766, ksi[2][0, 0]);
            Assert.AreEqual(0.13403066458729723, ksi[2][0, 1]);
            Assert.AreEqual(0.06694007875078023, ksi[2][1, 0]);
            Assert.AreEqual(0.75307588594627772, ksi[2][1, 1]);
            Assert.AreEqual(1d, ksi[2].Sum());
        }