Tensorflow2.0 Tensorflow_addons实现CRF(条件随机场)

最近想使用TF2.0实现一下命名实体识别,但是不大知道条件随机场该怎么实现,在网上搜了一下也没看到。今早吃饭的时候还在想我一定要亲自实现TF2版本的条件随机场。结果就在上课的时候突然发现了谷歌把contrib迁移到Tensorflow_addons里面

import tensorflow_addons as tfa
import tensorflow as tf
import numpy as np

inputs=tf.random.truncated_normal([2,10,5])
target=tf.convert_to_tensor(np.random.randint(5,size=(2,10)),dtype=tf.int32)
out=tf.keras.layers.Softmax(inputs)

lens=tf.convert_to_tensor([9,6],dtype=tf.int32)
log_likelihood,tran_paras=tfa.text.crf_log_likelihood(inputs, target, lens)
batch_pred_sequence,batch_viterbi_score=tfa.text.crf_decode(inputs,tran_paras,lens)
loss=tf.reduce_sum(-log_likelihood)
print('log_likelihood is :',log_likelihood.numpy())
print('batch_pred_sequence is :',batch_pred_sequence.numpy())
print('loss is :',loss.numpy())
log_likelihood is : [-21.722277 -11.170404]
batch_pred_sequence is : [[0 0 2 4 0 3 4 0 3 0],
                          [2 0 2 4 4 3 4 4 4 4]]
loss is : 32.89268

在使用的时候,要把这个嵌入到自己的模型里面去,使用损失训练模型

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值