java分层hashmap n阶hmm实现

w8biq8rn  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(336)

我已经实现了一阶,二阶和三阶隐马尔可夫模型使用哈希Map,而不是转移矩阵。我使用这些hmm来计算在1个音符/2个音符/3个音符之后出现的音符(建模为整数0-128)的数量,这取决于顺序。
例如,第二顺序的实现是:

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。我尝试过使用多态性,但每次都会遇到类castexception。不完全确定如何在这个问题上使用泛型。我猜的诀窍是知道何时在最后一个hashmap上,这样就可以更新count double值。
任何建议都太好了!

balp4ylt

balp4ylt1#

我用对象继承和递归解决了这个问题。现在通过迭代学习数据中的注解并对每个注解调用此函数来更新权重。
传递给函数 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);
        }
    }
}

相关问题