HMM的Viterbi算法C#實現

d3fw 9年前發布 | 914 次閱讀 C# 算法

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Viterbi  
{  
    class Program  
    {  
        const int m = 2;  //隱含狀態數  
        const int n = 3;  //觀察狀態數  
        static int[] sArray = new int[n];  //隱含狀態序列  
        static int[] oArray = { 0, 1, 2 };  //可觀察狀態序列  
        static double[] iArray = { 0.6, 0.4 };//初始概率矩陣  
        static double[,] aArray = { { 0.7, 0.3 }, { 0.4, 0.6 } };//轉移概率矩陣  
        static double[,] bArray = { { 0.5, 0.4, 0.1 }, { 0.1, 0.3, 0.6 } };//發射概率矩陣  
        static double[,] resultArray = new double[n, m];//保存結果   

        static void Main(string[] args)  
        {  
            Viterbi(sArray, oArray, iArray, aArray, bArray);  
            foreach (int i in sArray)  
            {  
                Console.Write(i);  
            }  
            Console.ReadKey();  
        }  

        static void Viterbi(int[] s, int[] o, double[] i, double[,] a, double[,] b)  
        {  
            for (int j = 0; j < m; j++)  
            {  
                resultArray[0, j] = iArray[j] * bArray[j, oArray[0]];  
            }  
            for (int j = 1; j < n; j++)  
            {  
                for (int p = 0; p < m; p++)  
                {  
                    for (int k = 0; k < m; k++)  
                    {  
                        double tmp = resultArray[j - 1, p] * aArray[p, k] * bArray[k, oArray[j]];  
                        if (tmp > resultArray[j, k])  
                            resultArray[j, k] = tmp;  
                    }  
                }  
            }  
            for (int j = 0; j < n; j++)  
            {  
                double tmp = resultArray[j, 0];  
                sArray[j] = 0;  
                for (int p = 0; p < m; p++)  
                {  
                    if (resultArray[j, p] > tmp)  
                        sArray[j] = p;  
                }  
            }  
        }  
    }  
}  </pre> 


 本文由用戶 d3fw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!