0
1

単純マルコフ連鎖のPython実装

Posted at

参考文献

Pythonで学ぶ はじめてのAIプログラミング
自然言語処理と音声処理
著者 小高 知宏
発売日 2020/09/23

準備

オンラインコンパイラを使用します。

プログラム

sample.py
import numpy as np

# 乱数列を生成
np.random.seed(0)  # 再現性のためにシードを設定
random_sequence = np.random.randint(0, 100, size=10)
print("乱数列:", random_sequence)

# 状態を割り当てる関数
def assign_state(diff):
    if diff > 0:
        return 2  # 高い時
    elif diff == 0:
        return 1  # 同じ時
    else:
        return 0  # 低い時

# 前後の差を計算し、状態を割り当てる
states = [assign_state(random_sequence[i] - random_sequence[i-1]) for i in range(1, len(random_sequence))]
print("状態:", states)

# 状態遷移行列を初期化
transition_matrix = np.zeros((3, 3))

# 状態遷移をカウント
for (current_state, next_state) in zip(states[:-1], states[1:]):
    transition_matrix[current_state, next_state] += 1

# 状態遷移確率を計算
transition_probabilities = transition_matrix / transition_matrix.sum(axis=1, keepdims=True)
print("状態遷移確率行列:\n", transition_probabilities)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1