python分词训练_CRF算法学习——自己动手实现Bi-LSTM+CRF分词(python)

意图识别 <= Bi-LSTM+CRF <= 先懂CRF <= 先懂HMM <= 先懂EM

终于到这一步了,这一次要用python写了,使用tensorflow去写。关于tensorflow的使用不是我的重点。

相关代码还是在我的GitHub上。

题外话,idea可以安装一个python插件,然后设置一下python编译器,这样就可以在项目里既能运行java又能运行python了,美滋滋。

Bi-LSTM+CRF分词实现路线图

由于不是很会写python(就会用tensorflow....),所以开始实现的代码比较ugly,然后又仿造着github比较好的项目重写了一版,所以有两个文件夹:uglybilstmcrf和bilstmcrf

思路

1.所有字构建字典,同时所有字变成字嵌入(可以利用gensim预训练字向量,也可以到时候随机生成)

2.得到字嵌入后,用字嵌入特征喂给双向LSTM

3.然后加一个CRF层,最小化CRF极大似然得到的对数极大似然值

4.训练结束以后,得到转移矩阵和Bi-LSTM的参数,直接利用viterbi解码

对着代码讲如何实现

这一部分用的bilstmcrf里面的代码,ugly的看看就好

首先定义一些占位符

word_ids是就是每个字对应的字典的id形成的list

比如“我爱北京天安门”这7个字,可能就会变成[305,249,70,291,58,131,254]这样的id序列。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BERT-BiLSTM-CRF是一种基于深度学习的中文分词方法,它结合了BERT预训练模型、双向长短时记忆网络(BiLSTM)和条件随机场(CRF)模型。具体流程如下: 1. 预处理:将中文文本转换为字符序列,并将每个字符转换为对应的向量表示。 2. BERT编码:使用BERT模型对字符序列进行编码,得到每个字符的上下文表示。 3. BiLSTM编码:将BERT编码后的字符向量输入到双向LSTM中,得到每个字符的上下文表示。 4. CRF解码:使用CRF模型对BiLSTM编码后的结果进行解码,得到最终的分词结果。 以下是BERT-BiLSTM-CRF中文分词Python代码示例: ```python import torch import torch.nn as nn from transformers import BertModel class BertBiLSTMCRF(nn.Module): def __init__(self, bert_path, num_tags): super(BertBiLSTMCRF, self).__init__() self.bert = BertModel.from_pretrained(bert_path) self.lstm = nn.LSTM(input_size=self.bert.config.hidden_size, hidden_size=self.bert.config.hidden_size // 2, num_layers=1, bidirectional=True, batch_first=True) self.dropout = nn.Dropout(p=0.5) self.fc = nn.Linear(self.bert.config.hidden_size, num_tags) self.crf = CRF(num_tags) def forward(self, input_ids, attention_mask): bert_output = self.bert(input_ids=input_ids, attention_mask=attention_mask)[0] lstm_output, _ = self.lstm(bert_output) lstm_output = self.dropout(lstm_output) emissions = self.fc(lstm_output) return emissions def loss(self, input_ids, attention_mask, tags): emissions = self.forward(input_ids, attention_mask) loss = self.crf(emissions, tags, mask=attention_mask.byte(), reduction='mean') return -loss def decode(self, input_ids, attention_mask): emissions = self.forward(input_ids, attention_mask) return self.crf.decode(emissions, attention_mask.byte()) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值