public void viterbiInference ( List seq ) { int i , j , k ; int seqLen = seq . size ( ) ; if ( seqLen <= 0 ) { return ; } if ( memorySize < seqLen ) { allocateMemory ( seqLen ) ; } // compute Vi for the first position in the sequence computeVi ( seq , 0 , Vi , true ) ; for ( j = 0 ; j < numLabels ; j ++ ) { memory [ 0 ] [ j ] . first = Vi . vect [ j ] ; memory [ 0 ] [ j ] . second = j ; } // scaling for the first position divide ( memory [ 0 ] , sum ( memory [ 0 ] ) ) ; // the main loop for ( i = 1 ; i < seqLen ; i ++ ) { // compute Vi at the position i computeVi ( seq , i , Vi , true ) ; // for all possible labels at the position i for ( j = 0 ; j < numLabels ; j ++ ) { memory [ i ] [ j ] . first = 0.0 ; memory [ i ] [ j ] . second = 0 ; // find the maximal value and its index and store them in memory // for later tracing back to find the best path for ( k = 0 ; k < numLabels ; k ++ ) { double tempVal = memory [ i - 1 ] [ k ] . first * Mi . mtrx [ k ] [ j ] * Vi . vect [ j ] ; if ( tempVal > memory [ i ] [ j ] . first ) { memory [ i ] [ j ] . first = tempVal ; memory [ i ] [ j ] . second = k ; } } } // scaling for memory at position i divide ( memory [ i ] , sum ( memory [ i ] ) ) ; } // viterbi backtrack to find the best label path int maxIdx = findMax ( memory [ seqLen - 1 ] ) ; ( ( Observation ) seq . get ( seqLen - 1 ) ) . modelLabel = maxIdx ; for ( i = seqLen - 2 ; i >= 0 ; i -- ) { ( ( Observation ) seq . get ( i ) ) . modelLabel = memory [ i + 1 ] [ maxIdx ] . second ; maxIdx = ( ( Observation ) seq . get ( i ) ) . modelLabel ; } }
Viterbi inference .