作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试模拟给定转换矩阵的数据。我使用 this answered question 制作了转换矩阵,假设我的数据是:
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
创建长度为 的链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']
关于python - 从转移矩阵生成马尔可夫链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59858123/
我在学习道路上遇到了一项任务。 对于均值 μ=np 和方差 σ**2=np(1−p) 的二项式分布 X∼Bp,n,我们希望上限概率 P (X≥c⋅μ) 对于 c≥1。三界介绍: Formulas 任务
给定以下马尔可夫矩阵: import numpy, scipy.linalg A = numpy.array([[0.9, 0.1],[0.15, 0.85]]) 平稳概率存在且等于[.6, .4]。
我是一名优秀的程序员,十分优秀!