Python&数学基礎

マルコフ連鎖


プログラム(Python 3.10.4)


    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import numpy as np
    import pandas as pd
    import random

    
    def markov():
        m = 5
        number = [i+1 for i in range(m)]
        choice_list = ["A", "B", "C"]
        markov_list = random.choices(choice_list, k=m)
        result_list = []
        P = np.array([[0.4, 0.5, 0.1], [0.3, 0.3, 0.4], [0.6, 0.2, 0.2]])
        Pn = P
        for n in range(m):
            if markov_list[n] == "A":
                result_list.append(round(Pn[0][0],2))
            elif markov_list[n] == "B":
                result_list.append(round(Pn[0][1],2))
            elif markov_list[n] == "C":
                result_list.append(round(Pn[0][2],2))
            Pn = Pn @ P
        number.insert(0, "N")
        markov_list.insert(0, "")
        result_list.insert(0, "P")
        table_list = [number, markov_list, result_list]
        ax_table.table(cellText=table_list, cellLoc="center", loc="center")
        plt.show()