Skip to content Skip to sidebar Skip to footer

Generating Markov Chain From Transition Matrix

I'm trying to simulate data given a transition matrix. I made the transition matrix using this answered question, so let's say my data is: days=['rain', 'rain', 'rain', 'clouds', '

Solution 1:

The following functions should work - get_next_term generates the next term in the chain given a transition matrix and the preceeding term, and make_chain creates a chain of length n given a transition matrix and the initial term.

Code:

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

Usage:

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

With your data:

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

Post a Comment for "Generating Markov Chain From Transition Matrix"