LSTM + CRF Viterbi decoding process

Title: Given a sequence of length n, m is a number of labels (label value is expressed as 1,2, ...., m), emission probability matrix E (n * m), where E [i] [j] denotes the i-th emission probability is predicted word label j, the transition probability matrix T (m * m), where T [i] [j] is transferred to the label i j labels the transition probability. He asked to return to the optimal sequence annotation result (an array res, res [i] denotes the i-th word label value marked).

public class Solution {
    
    public int[] getBestPath(int m, int n, double[][] E, double[][] T) {
        double[][] dp = new double[n + 1][m + 1];
        int[][] his = new int[n + 1][m + 1];
        for (int j = 1; j <= m; j++) {
            dp[1][j] = E[1][j];
        }
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= m ; j++) {
                for (int k = 1; k <= m; k++) {
                    double score = dp[i - 1][k] + T[k][j] + E[i][j];
                    if (score > dp[i][j]) {
                        dp[i][j] = score;
                        his[i][j] = k;
                    }
                }
            }
        }

        int label = 0;
        double min = Double.MIN_VALUE;

        for (int j = 1; j <= m; j++) {
            if (dp[n][j] > min) {
                label = j;
                min = dp[n][j];
            }
        }

        int[] res = new int[n + 1];
        for (int i = n; i >= 1; i--) {
            res[i] = label;
            label = his[i][label];
        }
        return res;
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/coldyan/p/11334729.html