马氏链:找到从A点到B点的最可能路径

问题描述

我有一个使用字典的转换矩阵

{'hex1': {'hex2': 1.0},'hex2': {'hex4': 0.4,'hex7': 0.2,'hex6': 0.2,'hex1': 0.2},'hex4': {'hex3': 1.0},'hex3': {'hex6': 0.3333333333333333,'hex2': 0.6666666666666666},'hex6': {'hex1': 0.3333333333333333,'hex4': 0.3333333333333333,'hex5': 0.3333333333333333},'hex7': {'hex6': 1.0},'hex5': {'hex3': 1.0}}

表示从某个十六进制变为另一十六进制的概率(例如hex1的概率为1的hex2hex2的概率为0.4的hex4

以起点和终点,我想找到可能性最高的路径。

代码的结构看起来像

def find_most_probable_path(start_hex,end_hex,max_path):
    path = compute for maximum probability path from start_hex to end_hex
    return path

其中max_path是要遍历的最大十六进制。如果max_path中没有路径,则返回空/空。另外,如果返回到起始十六进制,则在到达终止十六进制之前,请降低路径。

例如

find_most_probable_path(hex2,hex3,5)
>> "hex2,hex4,hex3"

输出可以是十六进制列表,也可以只是连接的字符串。

解决方法

您可以将Markov链视为有向加权图,并将概率用作图边缘权重。

这时,您可以使用Dijkstra算法获得加权图中两个点的最短路径。

https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

,

我开发了一种算法,但是我不知道它的效率,但是效果很好。

table={'hex1': {'hex2': 1.0},'hex2': {'hex4': 0.4,'hex7': 0.2,'hex6': 0.2,'hex1': 0.2},'hex4': {'hex3': 1.0},'hex3': {'hex6': 0.3333333333333333,'hex2': 0.6666666666666666},'hex6': {'hex1': 0.3333333333333333,'hex4': 0.3333333333333333,'hex5': 0.3333333333333333},'hex7': {'hex6': 1.0},'hex5': {'hex3': 1.0}}

def find_most_probable_path(start_hex,end_hex,max_path=0):
    assigned=[start_hex]
    foundTrue=False
    prob=[{"nodes":[start_hex],"prob":1,"length":1}]
    if max_path==0:
        status=False
    else:
        status=True
    while status==True:
        chn=[]
        status=False
        for i in prob:
            if i["length"]<max_path:
                lastElement=i["nodes"][-1]
                for j in table[lastElement]:
                    if j not in assigned:
                        temp=i.copy()
                        js=temp["nodes"].copy()
                        js.append(j)
                        temp["nodes"]=js
                        temp["prob"]=temp["prob"]*table[lastElement][j]
                        temp["length"]+=1
                        #print(temp)
                        chn.append(temp)
                        status=True
        maxv=0
        for i in chn:
            if i["prob"]>=maxv:
                maxv=i["prob"]
                added=i
        if added["nodes"][-1]==end_hex:
            foundTrue=True
            status=False
        assigned.append(added["nodes"][-1])
        prob.append(added)
    if foundTrue==True:
        return prob[-1]["nodes"]
    else:
        return None


print(find_most_probable_path("hex2","hex3",5))

输出将是:

['hex2','hex4','hex3']

如果要查看路径的可能性,可以更改部分:

if foundTrue==True:
    return prob[-1]["nodes"]

收件人:

if foundTrue==True:
    return prob[-1]

然后程序给出如下输出:

{'nodes': ['hex2','hex3'],'prob': 0.4,'length': 3}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...