赞
踩
- # -*- coding: utf-8 -*-
- import numpy as np
- from random import random
-
-
- #转移矩阵
- trans_matrix = np.array(
- [[0.5 , 0.1 , 0.25 , 0.05],
- [0.15 , 0.5 , 0.2 , 0.05],
- [0.1 , 0.2 , 0.5 , 0.4],
- [0.25 , 0.2 , 0.05 , 0.5 ]])
-
-
-
-
- #数据
- dt = np.array([[0] , [1] , [0] , [0]])
- #进行转换
- res = np.dot(trans_matrix,dt)
- res = np.dot(trans_matrix , res) #50次
- '''
- #执行50次后,基本稳定
- array([[ 0.22720144],
- [ 0.21947408],
- [ 0.31993815],
- [ 0.23338634]])
- '''
-
-
-
-
-
-
- #真实模拟
- #状态计数器, 四个数分别代表停留在此状态的次数
- cnt_list = [0 , 0 , 0 , 0] # 0 1 2 3
- #初始状态 0 1 2 3 随意
- origin = 2
-
-
- #当前状态设为初始状态
- now = origin
- cnt = 0
- while True :
- #进行1000000次状态转移
- cnt += 1
- if cnt > 1000000 :
- break
-
- #抽取一个随机数(0到1 之间),我们根据其所在区间来确定下一个状态
- rand_num = random()
- #计算下一个状态
- next_status = 0
- #用来累加概率
- num_accu = 0.0
- for status_to_be in range(0 , 4) :
- num_accu += trans_matrix[status_to_be][now]
- #如果累加概率大于上面的随机数
- if rand_num <= num_accu :
- #选定为下一个状态
- next_status = status_to_be
- break
- #状态转移
- now = next_status
- #此状态计算加一
- cnt_list[now] += 1
-
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
#状态转移的计数结果应该与上面的概率是接近的,这就是马尔可夫链的含义
#状态分布概率只与转移矩阵有关,与初始状态无关
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。