算法實現系列第五章.viterbi算法

package algorithm;

public class Viterbi {
/**
* 維特比算法(Viterbi algorithm)是一種動態規劃算法。它用於尋找最有可能產生觀測事件序列的-維特比路徑-隱含狀態序列,特別是在馬爾可夫信息源上下文和隱馬爾可夫模型中。
術語“維特比路徑”和“維特比算法”也被用於尋找觀察結果最有可能解釋相關的動態規劃算法。例如在統計句法分析中動態規劃算法可以被用於發現最可能的上下文無關的派生(解析)的字符串,有時被稱爲“維特比分析”。
* @param args
*/
public static void main(String[] args) {
// 用分詞舉例有如下結構.採用少詞方式
// 0 中 中國 中國人
// 1 國 國人
// 2 人 人民
// 構建一個數組將如上結構放入數組中

Node begin = new Node("B", 0);
begin.score = 1 ;
Node end = new Node("END", 5);
Node[][] graph = new Node[6][0];
graph[0] = new Node[] { begin };
graph[1] = new Node[] { new Node("中", 1), new Node("中國", 1), new Node("中國人", 1) };
graph[2] = new Node[] { new Node("國", 2), new Node("國人", 2) };
graph[3] = new Node[] { new Node("人", 3), new Node("人民", 3) };
graph[4] = new Node[] { new Node("民", 4) };
graph[5] = new Node[] { end };

int to = 0;
Node node = null;

// viterbi尋找最優路徑
for (int i = 0; i < graph.length - 1; i++) {
for (int j = 0; j < graph[i].length; j++) {
node = graph[i][j];
to = node.getTo();
for (int k = 0; k < graph[to].length; k++) {
graph[to][k].setFrom(node);
}
}
}

// 反向遍歷尋找結果
node = graph[5][0];
while ((node = node.getFrom()) != null) {
System.out.println(node.getName());
}

}

static class Node {
private String name;
private Node from;
private int offe;
private Integer score;

public Node(String name, int offe) {
this.name = name;
this.offe = offe;
}

public Node(Node node, Node node2, Node node3) {
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Node getFrom() {
return from;
}

public void setFrom(Node from) {
if (this.score == null) {
this.score = from.score + 1;
this.from = from;
} else if (this.score > from.score + 1) {
this.score = from.score + 1;
this.from = from;
}
}

public int getTo() {
return this.offe + name.length();
}

}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章