// make sure the pseudo count is not zero
pseudoCount = (pseudoCount == 0) ? Double.MIN_VALUE : pseudoCount;
// initialize parameters
DenseMatrix transitionMatrix = new DenseMatrix(nrOfHiddenStates,
nrOfHiddenStates);
DenseMatrix emissionMatrix = new DenseMatrix(nrOfHiddenStates,
nrOfOutputStates);
DenseVector initialProbabilities = new DenseVector(nrOfHiddenStates);
// assign pseudo count to avoid zero probabilities
transitionMatrix.assign(pseudoCount);
emissionMatrix.assign(pseudoCount);
initialProbabilities.assign(pseudoCount);
// now loop over the sequences to count the number of transitions
Iterator<int[]> hiddenSequenceIt = hiddenSequences.iterator();
Iterator<int[]> observedSequenceIt = observedSequences.iterator();
while (hiddenSequenceIt.hasNext() && observedSequenceIt.hasNext()) {
// fetch the current set of sequences
int[] hiddenSequence = hiddenSequenceIt.next();
int[] observedSequence = observedSequenceIt.next();
// increase the count for initial probabilities
initialProbabilities.setQuick(hiddenSequence[0], initialProbabilities
.getQuick(hiddenSequence[0]) + 1);
countTransitions(transitionMatrix, emissionMatrix, observedSequence,
hiddenSequence);
}
// make sure that probabilities are normalized
double isum = 0; // sum of initial probabilities
for (int i = 0; i < nrOfHiddenStates; i++) {
isum += initialProbabilities.getQuick(i);
// compute sum of probabilities for current row of transition matrix
double sum = 0;
for (int j = 0; j < nrOfHiddenStates; j++) {
sum += transitionMatrix.getQuick(i, j);
}
// normalize current row of transition matrix
for (int j = 0; j < nrOfHiddenStates; j++) {
transitionMatrix.setQuick(i, j, transitionMatrix.getQuick(i, j) / sum);
}
// compute sum of probabilities for current row of emission matrix
sum = 0;
for (int j = 0; j < nrOfOutputStates; j++) {
sum += emissionMatrix.getQuick(i, j);
}
// normalize current row of emission matrix
for (int j = 0; j < nrOfOutputStates; j++) {
emissionMatrix.setQuick(i, j, emissionMatrix.getQuick(i, j) / sum);
}
}
// normalize the initial probabilities
for (int i = 0; i < nrOfHiddenStates; ++i) {
initialProbabilities.setQuick(i, initialProbabilities.getQuick(i) / isum);