栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Viterbi

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Viterbi

import numpy as np

#条件粘上,根据理论推导的结果,晴雨雨的概率最高
states = ('Rainy', 'Sunny')

observations = ('walk', 'shop', 'clean')

start_probability = {'Rainy': 0.6, 'Sunny': 0.4}

transition_probability = {
    'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3},
    'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6},
    }

emission_probability = {
    'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5},
    'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1},
}

#随机生成观测序列和状态序列    
def simulate(T):

    def draw_from(probs):

        return np.where(np.random.multinomial(1,probs) == 1)[0][0]
#不用int64会突然报错!报完错就废了!
    observations = np.zeros(T, dtype='int64')
    states = np.zeros(T, dtype='int64')
    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


def generate_index_map(lables):
    id2label = {}
    label2id = {}
    i = 0
    for l in lables:
        id2label[i] = l
        label2id[l] = i
        i += 1
    return id2label, label2id
 
states_id2label, states_label2id = generate_index_map(states)
observations_id2label, observations_label2id = generate_index_map(observations)

def convert_map_to_vector(map_, label2id):
#转换成一维数组
    v = np.zeros(len(map_), dtype=float)
    for e in map_:
        v[label2id[e]] = map_[e]
    return v

 
def convert_map_to_matrix(map_, label2id1, label2id2):
#转换成矩阵
    m = np.zeros((len(label2id1), len(label2id2)), dtype=float)
    for line in map_:
        for col in map_[line]:
            m[label2id1[line]][label2id2[col]] = map_[line][col]
    return m


A = convert_map_to_matrix(transition_probability, states_label2id, states_label2id)

B = convert_map_to_matrix(emission_probability, states_label2id, observations_label2id)

observations_index = [observations_label2id[o] for o in observations]
pi = convert_map_to_vector(start_probability, states_label2id)

observations_data, states_data = simulate(3)

print([states_id2label[index] for index in states_data])

['Sunny', 'Rainy', 'Rainy']
import paddle
D:ProgramDataAnaconda3libsite-packagessetuptoolsdistutils_patch.py:25: UserWarning: Distutils was imported before Setuptools. This usage is discouraged and may exhibit undesirable behaviors or errors. Please use Setuptools' objects directly or at least import Setuptools first.
  warnings.warn(
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/286345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号