如何在python代码的每次迭代中使用稳态概率来选择一个状态?

2024-09-27 19:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有三个状态的遍历马尔可夫链。我计算了稳态概率。 国家提出了我的问题。 我想解决n次迭代的问题,在每一次迭代中,我们根据计算出的稳态概率来选择输入。 换句话说,这和有三个特定概率的选项是一样的。我们希望在每次迭代中随机选择其中一个。在

你有什么建议吗??在

最好的, 艾桑


Tags: 状态选项国家概率建议稳态
1条回答
网友
1楼 · 发布于 2024-09-27 19:29:50

假设你有一个概率向量(而不是3),并且你的初始状态是第一个。在

import random

def markov(probs, iter):

  # normalize the probabilities
  total = sum(probs)
  probs = map(lambda e: float(e)/total, probs)

  # determine the number of states
  n = len(probs)

  # Set the initial state
  s = 0

  for i in xrange(iter):

    thresh = random.random()
    buildup = 0

    # When the sum of our probability vector is greater than `thresh`
    # we've found the next state
    for j in xrange(n):

      buildup += probs[j]
      if buildup >= thresh:
        break

    # Set the new state
    s = j

  return s

因此

^{pr2}$

但这只返回最后一个状态。不过,用一个巧妙的技巧很容易解决这个问题。让我们把它变成发电机。我们只需要再多写一行,yield s。在

def markov(probs, iter):
  # ...
  for i in xrange(iter):

    # Yield the current state
    yield s

    # ...
    for j in xrange(n):
      # ...

现在,当我们调用markov时,我们无法立即得到响应。在

>>> g = markov([1,1,1], 100)
>>> g
<generator object markov at 0x10fce3280>

相反,我们得到一个generator object,它有点像“冻结”循环。您可以使用next来执行一次

>>> g.next()
1
>>> g.next()
1
>>> g.next()
2

甚至可以用list来放松整个过程

>>> list(markov([1,1,1], 100))
[0, 0, 1, 1, 0, 0, 0, 2, 1, 1, 2, 0, 1, 0, 0, 1, 2, 2, 2, 1, 2, 0, 1, 2, 0, 1, 2, 2, 2, 2, 1, 0, 0, 0, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 0, 0, 2, 2, 1, 0, 0, 0, 2, 0, 2, 2, 1, 0, 1, 1, 1, 2, 2, 2, 2, 0, 2, 1, 0, 0, 1, 2, 0, 0, 1, 2, 2, 0, 0, 1, 2, 1, 0, 0, 1, 0, 2, 1, 1, 0, 1, 1, 2, 2, 2, 1, 1, 0, 0, 0]

相关问题 更多 >

    热门问题