Tensorflow实现条件随机场

14 篇文章 0 订阅
1 篇文章 0 订阅

不讲原理,不将原始代码实现,一切都从调用tensorflow出发。

只有示例,没有讲解。

代码参考:TensorFlow-GitHub

import numpy as np
import tensorflow as tf


# 输入 batch=3, max_words=6, embedding=4
x = np.random.randn(3, 6, 4)
x[1, 4:] = 0

x_length = [6, 4, 6]

# tag_size=3, 
y = np.random.randint(3, size=[3, 6]).astype(np.int32)

embed_size = 4
tag_size = 3


# input datas
# assume b = batch, n = max_word, d = embed_size, t = tag_size
# shape = [batch, max_word, embed_size], also as [b, n, d]
inputs = tf.Variable(x, dtype=tf.float32)
# [b]
inputs_len = tf.Variable(x_length, dtype=tf.int32)
# [b, n]
targets = tf.Variable(y, dtype=tf.int32)

batch_size = tf.shape(inputs)[0]
max_word = tf.shape(inputs)[1]

# [d, t]
w = tf.Variable(tf.random_normal([embed_size, tag_size]))
# [t]
b = tf.Variable(tf.random_normal([tag_size]))

# [b*n, d]
inputs = tf.reshape(inputs, [-1, embed_size])
# [b*n, d]
unary_scors = tf.matmul(inputs, w) + b
# [b, n, t]
unary_scors = tf.reshape(unary_scors, [batch_size, max_word, tag_size])

# log_likelihood: [b]
# transition_params: [t, t]
log_likelihood, transition_params = tf.contrib.crf.crf_log_likelihood(unary_scors, targets, inputs_len)
loss = tf.reduce_mean(-log_likelihood)

# viterbi_sequence: [b, n]
# viterbi_score: [b]
viterbi_sequence, viterbi_score = tf.contrib.crf.crf_decode(unary_scors, transition_params, inputs_len)
pred = viterbi_sequence


with sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    sess.run(viterbi_sequence)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值