SoftMasked-bert文本纠错论文笔记以及代码实现

本文是Spelling Error Correction with Soft-Masked BERT论文的学习笔记,并且根据论文实现了相应的源码。

改进BERT纠错模型的motivation:BERT预训练模型只对于句子进行15%的mask字符进行预测,使得模型没有检测error的能力,从而更趋向于不纠错,即只复制原始字符

论文模型主体思想:

  1. 句子预处理,得到相应的字符的input embedding

  2. input embedding 经过detection 网络,输出得到句子序列每个位置的错误概率分布

  3. 根据得到的错误概率分布,计算input embdding 和MASK embedding 的权重,并得到soft-masked embedding

  4. 上述得到的embedding输入纠错BERT网络,输出得到每个位置上的纠错候选词

 

子网络解释

1.detection网络

  • 双向GRU得到前向和反向的隐状态,连接得到最终每个位置的隐状态表示hi

  • 隐状态hi经过线性sigmoid层得到可疑字概率ei,计算soft-embedding=ei*masked-embedding + (1-ei)*embedding。(ei代表错字的概率分数)

2.correction网络:跟正常BERT纠错网络一样

 

代码GitHub链接:https://github.com/will-wiki/softmasked-bert.git

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用PyTorch实现MC-BERT模型的示例代码: ```python import torch import torch.nn as nn from transformers import BertModel, BertTokenizer class MCBert(nn.Module): def __init__(self, bert_config): super(MCBert, self).__init__() self.bert = BertModel.from_pretrained('bert-base-uncased', config=bert_config) self.dropout = nn.Dropout(bert_config.hidden_dropout_prob) self.classifier = nn.Linear(bert_config.hidden_size, 1) def forward(self, input_ids, token_type_ids=None, attention_mask=None): outputs = self.bert(input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) return logits # 加载预训练模型和词汇表 tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') config = BertConfig.from_pretrained('bert-base-uncased') model = MCBert(config) # 输入文本 text = "Hello, how are you doing today?" # 将文本转换为输入特征 input_ids = tokenizer.encode(text, add_special_tokens=True) attention_mask = [1] * len(input_ids) # 将输入特征传入模型 logits = model(torch.tensor([input_ids]), attention_mask=torch.tensor([attention_mask])) # 打印输出 print(logits) ``` 在上面的示例代码中,我们首先定义了一个MC-BERT模型,包括一个BERT模型、一个dropout层和一个线性分类器。然后,我们加载了BERT的预训练模型和词汇表,并使用tokenizer将输入文本转换为输入特征。最后,我们将输入特征传入模型,并打印输出。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值