簡體   English   中英

從轉移矩陣生成馬爾可夫鏈

[英]Generating Markov Chain from transition matrix

我正在嘗試模擬給定轉換矩陣的數據。 我使用這個已回答的問題制作了轉換矩陣,所以假設我的數據是:

days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds', 
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun', 
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain', 
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain', 
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun', 
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun', 
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun', 
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain', 
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain', 
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

我使用以下方法創建轉換矩陣:

pd.crosstab(pd.Series(days[1:],name='Tomorrow'),
            pd.Series(days[:-1],name='Today'),normalize=1)

其中有輸出:

Today      clouds      rain       sun
Tomorrow                             
clouds    0.40625  0.230769  0.309524
rain      0.28125  0.423077  0.142857
sun       0.31250  0.346154  0.547619

現在,我想使用上面的矩陣生成輸出。 因此,假設我的隨機起點是“下雨”,那么輸出將是(例如):

[rain, rain, clouds, sun] 

不幸的是,我只能找到使用字典制作矩陣的解決方案。

編輯:我用過:

pd.crosstab(pd.Series(word[:-1],name='Current'),
            pd.Series(word[1:],name='Next'),normalize=0)

我自己的矩陣:

Next    a    b      c          d         e   f   g   h
Current                             
a      0.0  0.0 0.428571    0.571429    0.0 0.0 0.0 0.0
b      0.0  0.0 0.230769    0.769231    0.0 0.0 0.0 0.0
c      0.0  0.0 0.000000    0.000000    0.0 0.0 1.0 0.0
d      0.0  0.0 0.000000    0.000000    0.0 0.0 0.0 1.0
e      1.0  0.0 0.000000    0.000000    0.0 0.0 0.0 0.0
f      0.0  1.0 0.000000    0.000000    0.0 0.0 0.0 0.0
g      0.0  0.0 0.000000    0.000000    1.0 0.0 0.0 0.0
h      0.0  0.0 0.000000    0.000000    0.0 1.0 0.0 0.0

以下函數應該可以工作 - get_next_term在給定轉換矩陣和前一項的情況下生成鏈中的下一項,並且make_chain在給定轉換矩陣和初始項的make_chain創建長度為n的鏈。

代碼:

import random
def get_next_term(t_s):
    return random.choices(t_s.index, t_s)[0]

def make_chain(t_m, start_term, n):
    chain = [start_term]
    for i in range(n-1):
        chain.append(get_next_term(t_m[chain[-1]]))
    return chain

用法:

>>> make_chain(transition_mat, 'rain', 5)
['rain', 'rain', 'clouds', 'clouds', 'sun']

使用您的數據:

>>> make_chain(transition_mat2, 'a', 8)
['a', 'e', 'g', 'c', 'a', 'e', 'g', 'c']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM