C#でViterbiアルゴリズム

昔、C言語で作ったやつをなくしてしまったのでC#で書いてみました。HMM (Hidden Markov Model, 隠れマルコフモデル)において、最尤状態列を計算します。

かなりやっつけで書いてるの後でリファクタリングしたいなぁ。

    Dictionary<string, KeyValuePair<string, double>> T = new Dictionary<string, KeyValuePair<string, double>>();

    foreach (string state in states)
    {
        T.Add(state, new KeyValuePair<string,double>(state, sp[state]));
    }

    foreach (string output in observations)
    {
        Dictionary<string, KeyValuePair<string, double>> U = new Dictionary<string, KeyValuePair<string, double>>();

        foreach (string nextState in states)
        {
            string argmax = String.Empty;
            double valmax = 0;

            foreach (string sourceState in states)
            {
                KeyValuePair<string, double> kvp = T[sourceState];
                double p = ep[sourceState][output] * tp[sourceState][nextState];
                double prob = kvp.Value * p;

                if (prob > valmax)
                {
                    argmax = kvp.Key + "," + nextState;
                    valmax = prob;
                }
            }

            U.Add(nextState, new KeyValuePair<string, double>(argmax, valmax)); 
        }

        T = U;
    }