位置: IT常识 - 正文

NLP进阶,Bert+BiLSTM情感分析实战(nlp baseline)

编辑:rootadmin
NLP进阶,Bert+BiLSTM情感分析实战

推荐整理分享NLP进阶,Bert+BiLSTM情感分析实战(nlp baseline),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:nlp bvr,nlp bpe,nlp bpes,nlp bert,nlp bi,nlp进阶书籍,nlp bert,nlp bert,内容如对您有帮助,希望把文章链接给更多的朋友!

Bert+BiLSTM做情感分析

情感分析

情感分析一类的任务比如商品评价正负面分析,敏感内容分析,用户感兴趣内容分析、甚至安全领域的异常访问日志分析等等实际上都可以用文本分类的方式去做,情感分析的问题本质是个二分类或者多分类的问题。

什么是Bert?

BERT的全称为Bidirectional Encoder Representation from Transformers,是一个预训练的语言表征模型。它强调了不再像以往一样采用传统的单向语言模型或者把两个单向语言模型进行浅层拼接的方法进行预训练,而是采用新的masked language model(MLM),以致能生成深度的双向语言表征。

该模型有以下主要优点:

1)采用MLM对双向的Transformers进行预训练,以生成深层的双向语言表征。

2)预训练后,只需要添加一个额外的输出层进行fine-tune,就可以在各种各样的下游任务中取得state-of-the-art的表现。在这过程中并不需要对BERT进行任务特定的结构修改。

今天我们使用Bert+BiLSTM实现对菜品正负评价的情感分析预测!

数据集

数据集是我们搜集了一些菜品的正负评价,正面的评价标记为1,负面评价标记为0,将其保存为csv文件。

将数据集放在工程的根目录

下载预训练模型

下载地址:https://huggingface.co/bert-base-chinese/tree/main。

我们的数据集是中文,所以,选择中文的预训练模型,这点要注意,如果选择其他的可能会出现不收敛的情况。将下图中画红框的文件加载下来。

在工程的根目录,新建文件夹“bert_base_chinese”,将下载的模型放进去,如下图:

模型

思路:将bert做为嵌入层提取特征,然后传入BiLSTM,最后使用全连接层输出分类。创建bert_lstm模型,代码如下:

class bert_lstm(nn.Module): def __init__(self, bertpath, hidden_dim, output_size,n_layers,bidirectional=True, drop_prob=0.5): super(bert_lstm, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim self.bidirectional = bidirectional #Bert ----------------重点,bert模型需要嵌入到自定义模型里面 self.bert=BertModel.from_pretrained(bertpath) for param in self.bert.parameters(): param.requires_grad = True # LSTM layers self.lstm = nn.LSTM(768, hidden_dim, n_layers, batch_first=True,bidirectional=bidirectional) # dropout layer self.dropout = nn.Dropout(drop_prob) # linear and sigmoid layers if bidirectional: self.fc = nn.Linear(hidden_dim*2, output_size) else: self.fc = nn.Linear(hidden_dim, output_size) #self.sig = nn.Sigmoid() def forward(self, x, hidden): batch_size = x.size(0) #生成bert字向量 x=self.bert(x)[0] #bert 字向量 # lstm_out #x = x.float() lstm_out, (hidden_last,cn_last) = self.lstm(x, hidden) #print(lstm_out.shape) #[32,100,768] #print(hidden_last.shape) #[4, 32, 384] #print(cn_last.shape) #[4, 32, 384] #修改 双向的需要单独处理 if self.bidirectional: #正向最后一层,最后一个时刻 hidden_last_L=hidden_last[-2] #print(hidden_last_L.shape) #[32, 384] #反向最后一层,最后一个时刻 hidden_last_R=hidden_last[-1] #print(hidden_last_R.shape) #[32, 384] #进行拼接 hidden_last_out=torch.cat([hidden_last_L,hidden_last_R],dim=-1) #print(hidden_last_out.shape,'hidden_last_out') #[32, 768] else: hidden_last_out=hidden_last[-1] #[32, 384] # dropout and fully-connected layer out = self.dropout(hidden_last_out) #print(out.shape) #[32,768] out = self.fc(out) return out def init_hidden(self, batch_size): weight = next(self.parameters()).data number = 1 if self.bidirectional: number = 2 if (USE_CUDA): hidden = (weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().float().cuda(), weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().float().cuda() ) else: hidden = (weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().float(), weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().float() ) return hidden

bert_lstm需要的参数功6个,参数说明如下:

NLP进阶,Bert+BiLSTM情感分析实战(nlp baseline)

–bertpath:bert预训练模型的路径

–hidden_dim:隐藏层的数量。

–output_size:分类的个数。

–n_layers:lstm的层数

–bidirectional:是否是双向lstm

–drop_prob:dropout的参数

定义bert的参数,如下:

class ModelConfig: batch_size = 2 output_size = 2 hidden_dim = 384 #768/2 n_layers = 2 lr = 2e-5 bidirectional = True #这里为True,为双向LSTM # training params epochs = 10 # batch_size=50 print_every = 10 clip=5 # gradient clipping use_cuda = USE_CUDA bert_path = 'bert-base-chinese' #预训练bert路径 save_path = 'bert_bilstm.pth' #模型保存路径

batch_size:batchsize的大小,根据显存设置。

output_size:输出的类别个数,本例是2.

hidden_dim:隐藏层的数量。

n_layers:lstm的层数。

bidirectional:是否双向

print_every:输出的间隔。

use_cuda:是否使用cuda,默认使用,不用cuda太慢了。

bert_path:预训练模型存放的文件夹。

save_path:模型保存的路径。

配置环境

需要下载transformers和sentencepiece,执行命令:

conda install sentencepiececonda install transformers数据集切分

数据集按照7:3,切分为训练集和测试集,然后又将测试集按照1:1切分为验证集和测试集。

代码如下:

model_config = ModelConfig() data=pd.read_csv('caipindianping.csv',encoding='utf-8') result_comments = pretreatment(list(data['comment'].values)) tokenizer = BertTokenizer.from_pretrained(model_config.bert_path) result_comments_id = tokenizer(result_comments, padding=True, truncation=True, max_length=200, return_tensors='pt') X = result_comments_id['input_ids'] y = torch.from_numpy(data['sentiment'].values).float() X_train,X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, shuffle=True, stratify=y, random_state=0) X_valid,X_test,y_valid,y_test = train_test_split(X_test, y_test, test_size=0.5, shuffle=True, stratify=y_test, random_state=0)训练、验证和预测

训练详见train_model函数,验证详见test_model,单次预测详见predict函数。

代码和模型链接: https://download.csdn.net/download/hhhhhhhhhhwwwwwwwwww/36305682

本文链接地址:https://www.jiuchutong.com/zhishi/298469.html 转载请保留说明!

上一篇:机器学习中的预测评价指标MSE、RMSE、MAE、MAPE、SMAPE

下一篇:ChatGPT5是否会影响人类的发展和工作?

  • 公司更换营业执照需要多久
  • 劳务分包人是实际施工人吗
  • 单位购牙膏牙刷卫生纸怎么做账
  • 税屋网官网房屋
  • 会计中预付款余额是什么
  • 当月已抵扣的专用发票能作废吗
  • 增值税即征即退收入要交企业所得税吗
  • 建筑业预缴税款是什么意思
  • 净资产利润率等于净资产收益率吗
  • 返利红字发票怎么做账
  • 收到员工的罚款钱怎么写分录
  • 预付账款怎么做凭证
  • 劳保统筹费用
  • 维修变压器的维修方法
  • 事业单位对外投资涉及的主要科目有
  • 什么时候需要计提税金及附加
  • 广告公司可以开维修费吗
  • 出口已使用过的设备退税吗
  • 变更公司财务人员,需要本人去吗
  • 工程项目人工费比例
  • 公司年度财务报告怎么写
  • 去税局代开开专用发票需要带什么证件?
  • 事业单位接受捐赠的货币资金在财务会计中确认捐赠收入
  • 不抵扣的发票是什么发票
  • 会计管理制度范本
  • 计提本月短期借款利息1000元
  • php中实现文件的上传需要使用哪个全局变量
  • flash player用不了怎么办
  • json去除某个字段
  • typecho插件开发教程
  • 押金少退侵犯了哪条法律
  • 非货币性资产对外投资会计处理
  • 产品销售账务处理办法
  • php数组函数题目
  • 鸟瞰视野
  • php dom
  • 应收票据利息会计科目
  • 行政事业单位转让不动产
  • 小企业会计准则2023电子版
  • 一文讲清资产负债表中各个项目的来龙去脉
  • node安装配置环境变量
  • 资产基金的明细科目
  • 律师事务所执业证
  • 逾期超过一年
  • 增值税专用发票丢了怎么补救
  • wordpress图片大小设置
  • 变卖废旧物资的增值税税率
  • 投资款超过实收资本会计处理
  • 外贸企业主要做什么
  • 公司的财产保险业务
  • sql server 2008 安装文件
  • mysql创建数据库的操作步骤
  • 劳务税能退税吗
  • 以前年度损失如何记账
  • 流动资产周转率和总资产周转率
  • 经营范围之外的业务
  • 出口退税企业如何更正申报增值税
  • 投标保证金的计算
  • 普通日记账如何记账
  • 手机如何使用windows
  • tesmon.sys导致的蓝屏
  • 电脑bios启动项设置中文
  • linux打成zip包
  • windows7cmd命令不能执行
  • win7开机chkdsk
  • win8系统打开浏览器
  • win10系统桌面图标大小怎么设置
  • opensuse怎么安装软件
  • cocos2dx schedule
  • [置顶]游戏名 TentacleLocker
  • jqgrid分页pager
  • androidstudio webview
  • 浙江国税qzzn
  • 税务局风险防控形成长远
  • 学费报销找学校哪个部门
  • 消费税的纳税义务的发生时间是如何规定的
  • ca证书免费申请
  • 税务绩效管理4+4+4+n
  • 广东发票查验平台下载
  • 我国近十年财政支出结构占比
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设