warmber's Blog
  • Home
  • Categories
  • Tags
  • Archives

HMM模型初探

In [3]:
import numpy as np
In [42]:
# 对应状态集合Q
states = ('Healthy', 'Fever')
# 对应观测集合V
observations = ('normal', 'cold', 'dizzy')
# 初始状态概率向量π
start_probability = {'Healthy': 0.6, 'Fever': 0.4}
# 状态转移矩阵A
transition_probability = {
    'Healthy': {'Healthy': 0.7, 'Fever': 0.3},
    'Fever': {'Healthy': 0.4, 'Fever': 0.6},
}
# 观测概率矩阵B
emission_probability = {
    'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},
    'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6},
}
In [43]:
# 随机生成观测序列和状态序列    
def simulate(T):

    def draw_from(probs):
        """
        1.np.random.multinomial:
        按照多项式分布,生成数据
        >>> np.random.multinomial(20, [1/6.]*6, size=2)
                array([[3, 4, 3, 3, 4, 3],
                       [2, 4, 3, 4, 0, 7]])
         For the first run, we threw 3 times 1, 4 times 2, etc.  
         For the second, we threw 2 times 1, 4 times 2, etc.
        2.np.where:
        >>> x = np.arange(9.).reshape(3, 3)
        >>> np.where( x > 5 )
        (array([2, 2, 2]), array([0, 1, 2]))
        """
        return np.where(np.random.multinomial(1,probs) == 1)[0][0]

    observations = np.zeros(T, dtype=int)
    states = np.zeros(T, dtype=int)
    states[0] = draw_from(pi)
    observations[0] = draw_from(B[states[0],:])
    for t in range(1, T):
        states[t] = draw_from(A[states[t-1],:])
        observations[t] = draw_from(B[states[t],:])
    return observations, states
In [34]:
# n:一组实验的次数,pvals:出现每种可能性的概率,size:实验的组数
# output:多组实验结果,每组结果表示各个结果出现的次数
np.random.multinomial(n=5, pvals=[1/6.]*6, size=2)

x = np.arange(9).reshape(3,3)
# 返回元素大于4的索引,由于二维矩阵,故返回结果包含两个结果:x索引和y索引
print np.where(x > 4)
(array([1, 2, 2, 2]), array([2, 0, 1, 2]))
Comments
comments powered by Disqus

  • The difference of SVM and LR model »

Published

12 8, 2017

Category

note

Tags

  • python 1

Stay in Touch

Get Monthly Updates

  • Powered by Pelican. Theme: Elegant by Talha Mansoor