tensorflow 使用HMM的 viterbi 计算误差

1 篇文章 0 订阅
# observation:[batch_size,num_step,output_dims] 神经网络输出
# transition:[output_dims,output_dims] 转移矩阵
# pi:[batch_size,output_dims] 初始概率矩阵
def lstm_crf_viterbi(observation,transition,pi):
    batch_size = observation.shape[0].value
    num_step = observation.shape[1].value
    output_len = transition.shape[0].value
    previous = []   # [B,O]
    #记录最终路径
    all_path_tag_sequence = []
    batch_scores = []
    #记录最佳路径
    batch_argmax = [[] for b in xrange(batch_size)]
    for b in xrange(batch_size):
        previous.append(tf.transpose([observation[b][0]+pi[b]]))
    for b in xrange(batch_size):
        for x in  range(1,num_step): 
            r_pre =tf.transpose(tf.convert_to_tensor([previous[b] for i in range(output_len)]))
            r_obs = tf.convert_to_tensor([observation[b][x] for i in range(output_len)])
            scores = r_pre + transition + r_obs
            scores = tf.convert_to_tensor(scores)
            batch_argmax[b].append(tf.squeeze(tf.argmax(scores,1)))
            previous[b] = tf.reduce_max(scores,1) 
            previous[b] = tf.squeeze(previous[b])
    print(batch_argmax)
    #回溯 (仅最高分)
    for b in xrange(batch_size):
        best_path = [tf.argmax(previous[b])]
        for x in xrange(num_step-2,-1,-1):
            best_path.insert(0,batch_argmax[b][x][best_path[0]])
        all_path_tag_sequence.append(best_path)
    return previous,all_path_tag_sequence
    #previous:最高分
    #all_path_tag_sequence:最高分路径
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值