下面的脚本为给定列表生成概率矩阵:

transitions = ['A', 'B', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'B', 'A', 'D']

def rank(c):
   return ord(c) - ord('A')

T = [rank(c) for c in transitions]

#create matrix of zeros

M = [[0]*4 for _ in range(4)]

for (i,j) in zip(T,T[1:]):
   M[i][j] += 1

#now convert to probabilities:
for row in M:
   n = sum(row)
   if n > 0:
       row[:] = [f/sum(row) for f in row]

#print M:
for row in M:
   print(row)


输出

[0.0, 0.5, 0.0, 0.5]
[0.5, 0.25, 0.25, 0.0]
[0.0, 1.0, 0.0, 0.0]
[0.5, 0.0, 0.0, 0.5]


我现在想做相反的事情,并根据概率矩阵创建一个新的A B C D过渡列表。
我怎样才能做到这一点?

最佳答案

随机库的choices函数可能会有所帮助。由于该问题并不表示如何选择第一个字母,因此在这里选择它的可能性与原始列表的内容相同。

由于Python 3.6 random.choices接受带有权重的参数。严格地规范它们不是严格必要的。

import random

letter = random.choice(transitions)  # take a starting letter with the same weights as the original list
new_list = [letter]
for _ in range(len(transitions) - 1):
    letter = chr(random.choices(range(4), weights=M[rank(letter)])[0] + ord('A'))
    new_list.append(letter)
print(new_list)


可以对整个代码进行某种程度的概括,以使其适用于任何类型的节点,而不仅仅是连续的字母:

from _collections import defaultdict
import random

transitions = ['A', 'B', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'B', 'A', 'D']

nodes = sorted(set(transitions))  # a list of all letters used
M = defaultdict(int)  # dictionary counting the occurrences for each transition i,j)

for (i, j) in zip(transitions, transitions[1:]):
    M[(i, j)] += 1

# dictionary with for each node a list of frequencies for the transition to a next node
T = {i: [M[(i, j)] for j in nodes] for i in nodes}

# node = random.choice(transitions) # chose the first node randomly with the same probability as the original list
node = random.choice(nodes) # chose the first node randomly, each node with equal probability
new_list = [node]
for _ in range(9):
    node = random.choices(nodes, T[node])[0]
    new_list.append(node)

print(new_list)


示例输出:['D', 'A', 'D', 'A', 'D', 'D', 'A', 'D', 'A', 'B']

关于python - 在给定转移概率矩阵的情况下,如何生成随机序列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59468414/

10-12 22:23