Bert-LWAN pytorch版代码

本文介绍了一种基于Bert的大型多标签文本分类模型Bert-LWAN的PyTorch实现。该模型适用于包括少量和零样本标签的大规模多标签分类任务,并提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值