2016-03-28 20 views
1

我已經實現了使用HashMaps的一階,二階和三階隱馬爾可夫模型,而不是轉換矩陣。根據順序,我使用這些HMM計算1音符/ 2音符/ 3音符後音符的出現次數(建模爲0-128整數)。分層HashMap N階HMM實現

例如,對於二階的實現是:

public void updateWeigths(ArrayList<Note> notes, HashMap<Integer, HashMap<Integer, HashMap<Integer, Double>>> hm) { 
    for (int i=0; i<notes.size()-2; i++) { 
     int prevPitch1 = notes.get(i).getPitch(); 
     int prevPitch2 = notes.get(i+1).getPitch(); 
     int nextPitch = notes.get(i+2).getPitch(); 
     if (prevPitch1 > 0 && prevPitch2 > 0 && nextPitch > 0) { 
      if (hm.containsKey(prevPitch1)) { 
       HashMap<Integer, HashMap<Integer, Double>> nextMapping1 = hm.get(prevPitch1); 
       if (nextMapping1.containsKey(prevPitch2)){ 
        HashMap<Integer, Double> nextMapping2 = nextMapping1.get(prevPitch2); 
        if (nextMapping2.containsKey(nextPitch)) { 
         double prob = nextMapping2.get(nextPitch); 
         nextMapping2.put(nextPitch, prob+1); 
        } 
        else { 
         nextMapping2.put(nextPitch, 1.0); 
        } 
       } 
       else { 
        nextMapping1.put(prevPitch2, new HashMap<Integer, Double>()); 
       } 
      } 
      else { 
       hm.put(prevPitch1, new HashMap<Integer,HashMap<Integer,Double>>()); 
      } 
     } 
    } 
} 

我想要實現使用相同的模式任意順序HMM。我嘗試使用多態,但每次都得到ClassCastException。不完全確定如何在此上使用泛型。我猜的訣竅是知道你什麼時候在最後一個HashMap上,這樣你就可以更新計數Double值。

任何建議將是偉大的!

回答

0

我設法解決問題,使用對象的繼承和遞歸。現在通過迭代學習數據中的音符並在每個音符上調用該函數來更新權重。

對於您傳遞的HashMap<HashMap<Integer, Object>實例中的函數,該實例是包含轉換概率,HMM的順序和學習筆記數組中的音符索引的數據結構。

public void updateTransitionProb(Object mapping, int ord, int noteIndex) { 
    int note = notesList.get(noteIndex).getPitch(); 
    HashMap<Integer, Object> hm = (HashMap<Integer, Object>) mapping; 

    if (ord == 0) { 
     hm.put(note, (hm.get(note) != null) ? ((Double) hm.get(note)) + 1.0 : new Double(1.0)); 
    } 
    else { 
     if (hm.containsKey(note)) { 
      this.updateTransitionProb(hm.get(note), --ord, ++noteIndex); 
     } 
     else { 
      hm.put(note, new HashMap<Integer, Object>()); 
      this.updateTransitionProb(hm.get(note), --ord, ++noteIndex); 
     } 
    } 
}