Bert-LWAN pytorch版代码

Bert-LWAN pytorch版代码

模型来源《An Empirical Study on Large-Scale Multi-Label Text Classification Including Few and Zero-Shot Labels》

pytorch版代码地址:https://github.com/wcx881212/wcx881212.github.io/tree/Bert-LWAN
tensorflow版源码地址:https://github.com/iliaschalkidis/lmtc-emnlp2020

model 可参考CAML模型 来源《Explainable Prediction of Medical Codes from Clinical Text》

import torch
from torch.nn.init import xavier_uniform
from torch import nn
from torch.nn import functional as F
from transformers import AutoModel
from neural_networks.custom_layers.dropout import SpatialDropout
from neural_networks.custom_layers.masking import Camouflage

class Model(nn.Module):
    def __init__(self, n_classes=4654, dropout_rate=0.5):
        super(Model, self).__init__()
        self.bert = AutoModel.from_pretrained("bert-base-uncased")
        self.dropout = SpatialDropout(drop=dropout_rate)
        self.masking = Camouflage(mask_value=0)
        self.U = nn.Linear(768,n_classes)  # 输入 输出
        xavier_uniform(self.U.weight)
        self.final = nn.Linear(768,n_classes)
        xavier_uniform(self.final.weight)

    def forward(self,x_batch):
        bert_output = self.bert(x_batch)  # 32 512 768
        inner_out = self.dropout(bert_output[0])
        x = self.masking(inputs=[inner_out, bert_output[0]])  # 32 512 768
        alpha = F.softmax(torch.transpose(self.U(x),1,2), dim=-1)#32 4654 512
        m = alpha.matmul(x)#torch.Size([32, 4654, 768])
        # final layer classification
        y = self.final.weight.mul(m).sum(dim=2).add(self.final.bias)#torch.Size([32, 4654])
        y = torch.sigmoid(y)
        return y

实验数据
在这里插入图片描述

引用:通过BertForTokenClassification类,我们可以很容易地实现命名实体识别。而pytorch-crf是一个开源包,它实现了条件随机场(CRF)作为命名实体识别的一种传统方法。具体的操作流程是,先使用BiLstm输出(BatchSize, Sequence Length, 2*hidden_size),然后经过一个线性层得到(BatchSize, Sequence Length, tag_nums),可以考虑对tag_nums这个维度进行softmax。最后,将结果输入到CRF中,在前向传播中输出真实标签序列的分数,作为损失函数时需要加上一个负号。在预测时,可以通过调用decode方法得到(BatchSize, Sequence)的序列标签。 所以,bert-crf pytorch是指在Bert模型的基础上结合条件随机场(CRF)的一种命名实体识别方法,通过pytorch-crf这个开源包来实现。它的流程是先使用BiLstm对输入进行处理,然后通过线性层和softmax得到标签的概率,最后使用CRF来获得最终的标签序列。这种方法在实现命名实体识别任务上有很好的效果。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Pytorch: 命名实体识别: BertForTokenClassification/pytorch-crf](https://blog.csdn.net/Wangpeiyi9979/article/details/89599009)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值