nlp课设 - 基于BERT 的情感分类

基于BERT 的情感分类

主要论文:

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding(双向Transformer 的预训练)

核心技术:

Embedding 、Attention --> Transformer

任务简介、拟解决问题、网络结构、LOSS设定、实验结果、案例分析等

image-20240506151107743

关于使用Pytorch 的简单说明

image-20240506153108258

论文研究背景、成果及意义

情感极性分析 - 由粗到细

粗粒度的情感分析 (面向文档或者整个句子)

SemEval - 2014 的比赛的第四个子任务中基于 Aspect 的情感分类

  1. Aspect 提取 (aspect term extraction):识别句子中的方面或属性。
  2. 判断 Aspect 的情感倾向 (aspect term polarity):确定提取出的方面的情感是正面的还是负面的。
  3. 检测 Aspect 所属的类别 (aspect category detection):判断提取的方面属于哪一个预定义的类别。
  4. 判断 Aspect category 上的情感倾向 (aspect category polarity) ;例如:image-20240506152726780

state-of-the-art

image-20240506154128060

这里可以看到情感分类的最新论文image-20240506154023614

算力提升 – GPU 的发展

image-20240506163835388

带来了 多任务深度学习 – 并行计算 (BERT – 2019)

大一统模型 – BERT

Benchmarks - BERT 的主流影响力image-20240506154643191

image-20240506165238499

LlamBERT: Large-scale low-cost data annotation in NLP

23 Mar 2024 · Bálint Csanády, Lajos Muzsai, Péter Vedres, Zoltán Nádasdy, András Lukács · Edit social preview

Large Language Models (LLMs), such as GPT-4 and Llama 2, show remarkable proficiency in a wide range of natural language processing (NLP) tasks. Despite their effectiveness, the high costs associated with their use pose a challenge. We present LlamBERT, a hybrid approach that leverages LLMs to annotate a small subset of large, unlabeled databases and uses the results for fine-tuning transformer encoders like BERT and RoBERTa. This strategy is evaluated on two diverse datasets: the IMDb review dataset and the UMLS Meta-Thesaurus. Our results indicate that the LlamBERT approach slightly compromises on accuracy while offering much greater cost-effectiveness.

两个含义:

1 基于BERT 和RoBERTa 的微调

2 准确率有所下降(降低了成本)

模型发展历程

RNN

image-20240506165433733

梯度爆炸 和梯度消失的问题

LSTM

image-20240506165531010

LSTM 引入门控单元 一定程度上减少了 梯度消失(累乘 – > 乘(记忆细胞的累加)); 但是不能解决梯度爆炸

Bi - LSTM(双向LSTM 从算法or 结构进行改进)

image-20240506170108651

Attention

image-20240506170237813

QKW 得到得分矩阵 ;

SEQ2 SEQ

Transformer

image-20240506170414460

可并行的跨时代意义: 抽离了位置信息;

Bi - Transformer

image-20240506171104903

论文泛读

论文结构总览

  1. 摘要:介绍了研究主题是BERT模型的概述。
  2. 引言:论述了研究的重要性和必要性。
  3. 模型:探讨了BERT模型的基本结构和关键特点。
  4. 架构:详细介绍了采用Transformer技术的架构细节。
  5. 训练:描述了模型的训练方法,包括数据准备和训练过程。
  6. 数据集:解释了用于训练和测试模型的数据集特性。
  7. 定性评估:通过实际案例和应用来评估模型的表现。
  8. 讨论:分析了模型的限制和未来的研究方向。

摘要:

BERT(Bidirectional Encoder Representations from Transformers.)是一种新型的语言表示模型。与其他近期的语言表示模型(如 Peters et al., 2018a; Radford et al., 2018)不同,BERT 的设计目标是通过在所有层上同时考虑左右上下文,从未标注的文本中预训练深层的双向表示。因此,只需在预训练的 BERT 模型上增加一个输出层,就可以针对广泛的任务(如问题回答和语言推理)进行微调,而无需大幅修改特定任务的架构。

BERT 在概念上简单,实证上有效。它在十一个自然语言处理任务上取得了新的最佳效果,包括:

  • 将 GLUE 得分提升到 80.5%(绝对提高了 7.7 个百分点)
  • MultiNLI 准确率提升到 86.7%(绝对提高了 4.6 个百分点)
  • SQuAD v1.1 问题回答测试 F1 分数提升到 93.2(绝对提高了 1.5 个百分点)
  • SQuAD v2.0 测试 F1 分数提升到 83.1(绝对提高了 5.1 个百分点)。

论文结构:

image-20240506172213025

论文精读

  • 论文算法模型总览
  • 论文算法模型的细节
  • 论文算法模型细节2
  • 实验设置及结果分析
  • 论文总结

论文的算法总览

Attention+ Self- Attention +Transformer

论文算法模型的细节

Attention and more

image-20240506170237813

得到X 1 到X n 的每一个word 的weight;主要运用到机器翻译的模型

image-20240506191157613

image-20240506191405673

多头自注意力

image-20240506191541030

头越多 提取的特征越多 语义表达效果越强;这里可以类比一下TextCNN;不同角度的特征提取,侧重不同,相当于一句话我们通过不同的角度去理解

Transformer

image-20240506192718831

image-20240506192420594

dk 全连接层数的超参, Google给的解释是使模型更快的收敛;

PositionEncoding;

输入和输出一起放入模型进行训练;预测的时候需要输入一个占位符

TF 的叠加

image-20240506193223716

image-20240506193402734

image-20240506193504578

Pre-training and Fine Tuning

image-20240506194642592

Pre
Masked LM

80% of the time: Replace the word with the [MASK] token, e.g., my dog is hairy →
my dog is [MASK]

• 10% of the time: Replace the word with a random word, e.g., my dog is hairy → my
dog is apple

• 10% of the time: Keep the word unchanged, e.g., my dog is hairy → my dog is hairy. The purpose of this is to bias the
representation towards the actual observed
word.

注意在中文中需要进行一定的本土化改进, 例如针对词组进行 mask (WWM 全词)

Next Sentence

image-20240506194449342

Fine-Tuning

image-20240506190820371

Batch size: 16, 32

Learning rate (Adam): 5e-5, 3e-5, 2e-5

Number of epochs: 2, 3, 4

为什么需要进行微调? 怎么进行微调?

image-20240506200144424

预训练模型权重有可能与我的任务不匹配;调整输入数据和全连接层

实验设置

image-20240506200348614

实验数据

SST- 2 二分类情感分析

image-20240506200553303

SQuAD 斯坦福大学给出的阅读理解数据集

image-20240506200958603

image-20240506204017073

模型大小

it is also perhaps surprising that we are able to achieve such significant improvements on top of models which are already quite large relative to the existing literature. For example, the largest Transformer explored in Vaswani et al. (2017) is (L=6, H=1024, A=16)with 100M parameters for the encoder, and the largest Transformer we have found in the literatureis (L=64, H=512, A=2) with 235M parameters(Al-Rfou et al., 2018). By contrast, BERTBASE contains 110M parameters and BERTLARGE contains 340M parameters.

image-20240506205423808

we hypothesize that when the model is fine-tuned directly on the downstream tasks and uses only a very small number of randomly initialized additional parameters, the task specific models can benefit from the larger, more expressive pre-trained representations even when downstream task data is very small.

论文总结

A 关键点

  • 自注意力
  • 多头自注意力
  • Transformer (双向)

B 创新点(启发)

  1. 双向预训练 + Fine Tuning (可以针对数据较少的任务进行)
  2. 深度学习就是特征学习
  3. 规模

Results are presented in Table 7. BERTLARGE performs competitively with state-of-the-art methods. The best performing method concatenates the token representations from the top four hidden layers of the pre-trained Transformer, which is only 0.3 F1 behind fine-tuning the entire model. This demonstrates that BERT is effective for both fine tuning and feature-based approaches.

代码实现

下面的代码实现均展示Bert 结构的核心思路,并非全部可直接run 的码子;
完整代码见GitHub: https://github.com/boots-coder/ABSA-PyTorch

image-20240506212520120

how to Get Started With the Model

from transformers import AutoTokenizer, AutoModelForMaskedLMtokenizer = AutoTokenizer.from_pretrained("bert-base-chinese")model = AutoModelForMaskedLM.from_pretrained("bert-base-chinese")

预训练模型下载

image-20240506213958801

注意:开源版本不包含MLM任务的权重;如需做MLM任务,请使用额外数据进行二次预训练(和其他下游任务一样)。

模型简称语料Google下载百度网盘下载
RBT6, ChineseEXT数据[1]-TensorFlow(密码hniy)
RBT4, ChineseEXT数据[1]-TensorFlow(密码sjpt)
RBTL3, ChineseEXT数据[1]TensorFlow PyTorchTensorFlow(密码s6cu)
RBT3, ChineseEXT数据[1]TensorFlow PyTorchTensorFlow(密码5a57)
RoBERTa-wwm-ext-large, ChineseEXT数据[1]TensorFlow PyTorchTensorFlow(密码dqqe)
RoBERTa-wwm-ext, ChineseEXT数据[1]TensorFlow PyTorchTensorFlow(密码vybq)
BERT-wwm-ext, ChineseEXT数据[1]TensorFlow PyTorchTensorFlow(密码wgnt)
BERT-wwm, Chinese中文维基TensorFlow PyTorchTensorFlow(密码qfh8)
BERT-base, ChineseGoogle中文维基Google Cloud-
BERT-base, Multilingual CasedGoogle多语种维基Google Cloud-
BERT-base, Multilingual UncasedGoogle多语种维基Google Cloud-

[1] EXT数据包括:中文维基百科,其他百科、新闻、问答等数据,总词数达5.4B。

Code in Transformer

  1. 构造函数 (__init__)
    • embeddings:负责将输入的 token 转换为嵌入向量。
    • encoder:由多层自注意力(self-attention)模块组成,将输入嵌入进行编码处理。
    • pooler:负责提取整个句子的向量表示,可以通过 add_pooling_layer 参数控制是否使用。
  2. 输入和输出嵌入 (get_input_embeddings / set_input_embeddings)
    • 这些方法用于获取和设置输入嵌入参数。
  3. 剪枝 (_prune_heads)
    • 用于剪掉多头注意力机制中指定的注意力头以减少模型复杂性。
  4. 前向传播 (forward)
    • 接受多种输入参数,包括 token 编号、注意力掩码、输入嵌入等。
    • 通过对输入嵌入、编码器和池化层的应用,生成模型的输出。
    • 支持输出最后的隐藏状态、池化后的句子向量、隐藏状态序列、注意力权重等。
  5. 解码器模式
    • 如果模型配置为解码器,将增加一个跨注意力机制层,用于在编码器和解码器之间实现交互。
    • encoder_hidden_statesencoder_attention_mask 参数会在前向传播中被用于跨注意力机制。
class BertModel(BertPreTrainedModel):"""The model can behave as an encoder (with only self-attention) as wellas a decoder, in which case a layer of cross-attention is added betweenthe self-attention layers, following the architecture described in `Attention is all you need<https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.To behave as an decoder the model needs to be initialized with the:obj:`is_decoder` argument of the configuration set to :obj:`True`.To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`argument and :obj:`add_cross_attention` set to :obj:`True`; an:obj:`encoder_hidden_states` is then expected as an input to the forward pass."""def __init__(self, config, add_pooling_layer=True):super().__init__(config)self.config = configself.embeddings = BertEmbeddings(config)self.encoder = BertEncoder(config)self.pooler = BertPooler(config) if add_pooling_layer else Noneself.init_weights()def get_input_embeddings(self):return self.embeddings.word_embeddingsdef set_input_embeddings(self, value):self.embeddings.word_embeddings = valuedef _prune_heads(self, heads_to_prune):"""Prunes heads of the model.heads_to_prune: dict of {layer_num: list of heads to prune in this layer}See base class PreTrainedModel"""for layer, heads in heads_to_prune.items():self.encoder.layer[layer].attention.prune_heads(heads)@add_start_docstrings_to_callable(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))@add_code_sample_docstrings(tokenizer_class=_TOKENIZER_FOR_DOC,checkpoint="bert-base-uncased",output_type=BaseModelOutputWithPooling,config_class=_CONFIG_FOR_DOC,)def forward(self,input_ids=None,attention_mask=None,token_type_ids=None,position_ids=None,head_mask=None,inputs_embeds=None,encoder_hidden_states=None,encoder_attention_mask=None,output_attentions=None,output_hidden_states=None,return_dict=None,):r"""encoder_hidden_states  (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attentionif the model is configured as a decoder.encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):Mask to avoid performing attention on the padding token indices of the encoder input. This maskis used in the cross-attention if the model is configured as a decoder.Mask values selected in ``[0, 1]``:- 1 for tokens that are **not masked**,- 0 for tokens that are **maked**."""output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = (output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states)return_dict = return_dict if return_dict is not None else self.config.use_return_dictif input_ids is not None and inputs_embeds is not None:raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")elif input_ids is not None:input_shape = input_ids.size()elif inputs_embeds is not None:input_shape = inputs_embeds.size()[:-1]else:raise ValueError("You have to specify either input_ids or inputs_embeds")device = input_ids.device if input_ids is not None else inputs_embeds.deviceif attention_mask is None:attention_mask = torch.ones(input_shape, device=device)if token_type_ids is None:token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]# ourselves in which case we just need to make it broadcastable to all heads.extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)# If a 2D or 3D attention mask is provided for the cross-attention# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]if self.config.is_decoder and encoder_hidden_states is not None:encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)if encoder_attention_mask is None:encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)else:encoder_extended_attention_mask = None# Prepare head mask if needed# 1.0 in head_mask indicate we keep the head# attention_probs has shape bsz x n_heads x N x N# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)embedding_output = self.embeddings(input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds)encoder_outputs = self.encoder(embedding_output,attention_mask=extended_attention_mask,head_mask=head_mask,encoder_hidden_states=encoder_hidden_states,encoder_attention_mask=encoder_extended_attention_mask,output_attentions=output_attentions,output_hidden_states=output_hidden_states,return_dict=return_dict,)sequence_output = encoder_outputs[0]pooled_output = self.pooler(sequence_output) if self.pooler is not None else Noneif not return_dict:return (sequence_output, pooled_output) + encoder_outputs[1:]return BaseModelOutputWithPooling(last_hidden_state=sequence_output,pooler_output=pooled_output,hidden_states=encoder_outputs.hidden_states,attentions=encoder_outputs.attentions,)

Code WIth Me

logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stdout))class Instructor:def __init__(self, opt):self.opt = optif 'bert' in opt.model_name:tokenizer = Tokenizer4Bert(opt.max_seq_len, opt.pretrained_bert_name)bert = BertModel.from_pretrained(opt.pretrained_bert_name)self.model = opt.model_class(bert, opt).to(opt.device)else:tokenizer = build_tokenizer(fnames=[opt.dataset_file['train'], opt.dataset_file['test']],max_seq_len=opt.max_seq_len,dat_fname='{0}_tokenizer.dat'.format(opt.dataset))embedding_matrix = build_embedding_matrix(word2idx=tokenizer.word2idx,embed_dim=opt.embed_dim,dat_fname='{0}_{1}_embedding_matrix.dat'.format(str(opt.embed_dim), opt.dataset))self.model = opt.model_class(embedding_matrix, opt).to(opt.device)self.trainset = ABSADataset(opt.dataset_file['train'], tokenizer)self.testset = ABSADataset(opt.dataset_file['test'], tokenizer)assert 0 <= opt.valset_ratio < 1if opt.valset_ratio > 0:valset_len = int(len(self.trainset) * opt.valset_ratio)self.trainset, self.valset = random_split(self.trainset, (len(self.trainset) - valset_len, valset_len))else:self.valset = self.testsetif opt.device.type == 'cuda':logger.info('cuda memory allocated: {}'.format(torch.cuda.memory_allocated(device=opt.device.index)))self._print_args()def _print_args(self):n_trainable_params, n_nontrainable_params = 0, 0for p in self.model.parameters():n_params = torch.prod(torch.tensor(p.shape))if p.requires_grad:n_trainable_params += n_paramselse:n_nontrainable_params += n_paramslogger.info('n_trainable_params: {0}, n_nontrainable_params: {1}'.format(n_trainable_params, n_nontrainable_params))logger.info('> training arguments:')for arg in vars(self.opt):logger.info('>>> {0}: {1}'.format(arg, getattr(self.opt, arg)))def _reset_params(self):for child in self.model.children():if type(child) != BertModel:  # skip bert paramsfor p in child.parameters():if p.requires_grad:if len(p.shape) > 1:self.opt.initializer(p)else:stdv = 1. / math.sqrt(p.shape[0])torch.nn.init.uniform_(p, a=-stdv, b=stdv)def _train(self, criterion, optimizer, train_data_loader, val_data_loader):max_val_acc = 0max_val_f1 = 0global_step = 0path = Nonefor epoch in range(self.opt.num_epoch):logger.info('>' * 100)logger.info('epoch: {}'.format(epoch))n_correct, n_total, loss_total = 0, 0, 0# switch model to training modeself.model.train()for i_batch, sample_batched in enumerate(train_data_loader):global_step += 1# clear gradient accumulatorsoptimizer.zero_grad()inputs = [sample_batched[col].to(self.opt.device) for col in self.opt.inputs_cols]outputs = self.model(inputs)targets = sample_batched['polarity'].to(self.opt.device)loss = criterion(outputs, targets)loss.backward()optimizer.step()n_correct += (torch.argmax(outputs, -1) == targets).sum().item()n_total += len(outputs)loss_total += loss.item() * len(outputs)if global_step % self.opt.log_step == 0:train_acc = n_correct / n_totaltrain_loss = loss_total / n_totallogger.info('loss: {:.4f}, acc: {:.4f}'.format(train_loss, train_acc))val_acc, val_f1 = self._evaluate_acc_f1(val_data_loader)logger.info('> val_acc: {:.4f}, val_f1: {:.4f}'.format(val_acc, val_f1))if val_acc > max_val_acc:max_val_acc = val_accif not os.path.exists('state_dict'):os.mkdir('state_dict')path = 'state_dict/{0}_{1}_val_acc{2}'.format(self.opt.model_name, self.opt.dataset, round(val_acc, 4))torch.save(self.model.state_dict(), path)logger.info('>> saved: {}'.format(path))if val_f1 > max_val_f1:max_val_f1 = val_f1return pathdef _evaluate_acc_f1(self, data_loader):n_correct, n_total = 0, 0t_targets_all, t_outputs_all = None, None# switch model to evaluation modeself.model.eval()with torch.no_grad():for t_batch, t_sample_batched in enumerate(data_loader):t_inputs = [t_sample_batched[col].to(self.opt.device) for col in self.opt.inputs_cols]t_targets = t_sample_batched['polarity'].to(self.opt.device)t_outputs = self.model(t_inputs)n_correct += (torch.argmax(t_outputs, -1) == t_targets).sum().item()n_total += len(t_outputs)if t_targets_all is None:t_targets_all = t_targetst_outputs_all = t_outputselse:t_targets_all = torch.cat((t_targets_all, t_targets), dim=0)t_outputs_all = torch.cat((t_outputs_all, t_outputs), dim=0)acc = n_correct / n_totalf1 = metrics.f1_score(t_targets_all.cpu(), torch.argmax(t_outputs_all, -1).cpu(), labels=[0, 1, 2],average='macro')return acc, f1def run(self):# Loss and Optimizercriterion = nn.CrossEntropyLoss()_params = filter(lambda p: p.requires_grad, self.model.parameters())optimizer = self.opt.optimizer(_params, lr=self.opt.learning_rate, weight_decay=self.opt.l2reg)train_data_loader = DataLoader(dataset=self.trainset, batch_size=self.opt.batch_size, shuffle=True)test_data_loader = DataLoader(dataset=self.testset, batch_size=self.opt.batch_size, shuffle=False)val_data_loader = DataLoader(dataset=self.valset, batch_size=self.opt.batch_size, shuffle=False)self._reset_params()best_model_path = self._train(criterion, optimizer, train_data_loader, val_data_loader)self.model.load_state_dict(torch.load(best_model_path))self.model.eval()test_acc, test_f1 = self._evaluate_acc_f1(test_data_loader)logger.info('>> test_acc: {:.4f}, test_f1: {:.4f}'.format(test_acc, test_f1))def main():# Hyper Parametersparser = argparse.ArgumentParser()parser.add_argument('--model_name', default='bert_spc', type=str)parser.add_argument('--dataset', default='laptop', type=str, help='twitter, restaurant, laptop')parser.add_argument('--optimizer', default='adam', type=str)parser.add_argument('--initializer', default='xavier_uniform_', type=str)parser.add_argument('--learning_rate', default=2e-5, type=float, help='try 5e-5, 2e-5 for BERT, 1e-3 for others')parser.add_argument('--dropout', default=0.1, type=float)parser.add_argument('--l2reg', default=0.01, type=float) # L2正则化参数parser.add_argument('--num_epoch', default=3, type=int, help='try larger number for non-BERT models')parser.add_argument('--batch_size', default=16, type=int, help='try 16, 32, 64 for BERT models')parser.add_argument('--log_step', default=5, type=int)parser.add_argument('--embed_dim', default=300, type=int)parser.add_argument('--hidden_dim', default=300, type=int)parser.add_argument('--bert_dim', default=768, type=int)parser.add_argument('--pretrained_bert_name', default='bert-base-uncased', type=str)parser.add_argument('--max_seq_len', default=80, type=int)parser.add_argument('--polarities_dim', default=3, type=int)parser.add_argument('--hops', default=3, type=int)parser.add_argument('--device', default=None, type=str, help='e.g. cuda:0')parser.add_argument('--seed', default=None, type=int, help='set seed for reproducibility')parser.add_argument('--valset_ratio', default=0, type=float,help='set ratio between 0 and 1 for validation support')# The following parameters are only valid for the lcf-bert modelparser.add_argument('--local_context_focus', default='cdm', type=str, help='local context focus mode, cdw or cdm')parser.add_argument('--SRD', default=3, type=int,help='semantic-relative-distance, see the paper of LCF-BERT model')opt = parser.parse_args()if opt.seed is not None:random.seed(opt.seed)numpy.random.seed(opt.seed)torch.manual_seed(opt.seed)torch.cuda.manual_seed(opt.seed)torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = Falsemodel_classes = {'lstm': LSTM,'td_lstm': TD_LSTM,'tc_lstm': TC_LSTM,'atae_lstm': ATAE_LSTM,'memnet': MemNet,'bert_spc': BERT_SPC,# default hyper-parameters for LCF-BERT model is as follws:# lr: 2e-5# l2: 1e-5# batch size: 16# num epochs: 5}dataset_files = {'twitter': {'train': './datasets/acl-14-short-data/train.raw','test': './datasets/acl-14-short-data/test.raw'},'restaurant': {'train': './datasets/semeval14/Restaurants_Train.xml.seg','test': './datasets/semeval14/Restaurants_Test_Gold.xml.seg'},'laptop': {'train': './datasets/semeval14/Laptops_Train.xml.seg','test': './datasets/semeval14/Laptops_Test_Gold.xml.seg'}}input_colses = {'lstm': ['text_raw_indices'],'td_lstm': ['text_left_with_aspect_indices', 'text_right_with_aspect_indices'],'tc_lstm': ['text_left_with_aspect_indices', 'text_right_with_aspect_indices', 'aspect_indices'],'atae_lstm': ['text_raw_indices', 'aspect_indices'],'memnet': ['text_raw_without_aspect_indices', 'aspect_indices'],'bert_spc': ['text_bert_indices', 'bert_segments_ids'],}initializers = {'xavier_uniform_': torch.nn.init.xavier_uniform_,'xavier_normal_': torch.nn.init.xavier_normal,'orthogonal_': torch.nn.init.orthogonal_,}optimizers = {'adadelta': torch.optim.Adadelta,  # default lr=1.0'adagrad': torch.optim.Adagrad,  # default lr=0.01'adam': torch.optim.Adam,  # default lr=0.001'adamax': torch.optim.Adamax,  # default lr=0.002'asgd': torch.optim.ASGD,  # default lr=0.01'rmsprop': torch.optim.RMSprop,  # default lr=0.01'sgd': torch.optim.SGD,}opt.model_class = model_classes[opt.model_name]opt.dataset_file = dataset_files[opt.dataset]opt.inputs_cols = input_colses[opt.model_name]opt.initializer = initializers[opt.initializer]opt.optimizer = optimizers[opt.optimizer]opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') \if opt.device is None else torch.device(opt.device)log_file = '{}-{}-{}.log'.format(opt.model_name, opt.dataset, strftime("%y%m%d-%H%M", localtime()))logger.addHandler(logging.FileHandler(log_file))ins = Instructor(opt)ins.run()if __name__ == '__main__':main()
参数list

model Config :

“attention_probs_dropout_prob”: 0.1,
“finetuning_task”: null,
“hidden_act”: “gelu”,
“hidden_dropout_prob”: 0.1,
“hidden_size”: 768,
“initializer_range”: 0.02,
“intermediate_size”: 3072,
“layer_norm_eps”: 1e-12,
“max_position_embeddings”: 512,
“model_type”: “bert”,
“num_attention_heads”: 12,
“num_hidden_layers”: 12,
“num_labels”: 2,
“output_attentions”: false,
“output_hidden_states”: false,
“output_past”: true,
“pad_token_id”: 0,
“pruned_heads”: {},
“torchscript”: false,
“type_vocab_size”: 2,
“use_bfloat16”: false,
“vocab_size”: 30522

Parameters in True:

loading weights file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-pytorch_model.bin from cache at C:\Users\Administrator\.cache\torch\transformers\aa1ef1aede4482d0dbcd4d52baad8ae300e60902e88fcb0bebdec09afd232066.36ca03ab34a1a5d5fa7bc3d03d55c4fa650fed07220e2eeebc06ce58d0e9a157
cuda memory allocated: 439071232
n_trainable_params: 109484547, n_nontrainable_params: 0
> training arguments:
>>> model_name: bert_spc
>>> dataset: restaurant
>>> optimizer: <class 'torch.optim.adam.Adam'>
>>> initializer: <function xavier_uniform_ at 0x000002B8894F90D0>
>>> learning_rate: 2e-05
>>> dropout: 0.1
>>> l2reg: 0.01
>>> num_epoch: 3
>>> batch_size: 16
>>> log_step: 5
>>> embed_dim: 300
>>> hidden_dim: 300
>>> bert_dim: 768
>>> pretrained_bert_name: bert-base-uncased
>>> max_seq_len: 80
>>> polarities_dim: 3
>>> hops: 3
>>> device: cuda
>>> seed: None
>>> valset_ratio: 0
>>> local_context_focus: cdm
>>> SRD: 3
>>> model_class: <class 'models.bert_spc.BERT_SPC'>
>>> dataset_file: {'train': './datasets/semeval14/Restaurants_Train.xml.seg', 'test': './datasets/semeval14/Restaurants_Test_Gold.xml.seg'}
>>>

把这个cuda 给它利用起来!

下载命令行见官网:

https://pytorch.org/

image-20240508190921267

Some Q in coding part :

对于各个参数的理解:

  1. embed_dim: 嵌入层的维度,默认为 300 , how
  2. hidden_dim: 隐藏层的维度,默认为 300, how
  3. SRD: 语义相对距离(Semantic-Relative-Distance),LCF-BERT 模型的一个参数,默认为 3。

Result in Restarunt

image-20240508192928314

More Thinking

接下来有时间可以考虑做一个中文的情感细粒度分类,和数据的可视化展示; 以及分析一下最新的Bert 的改进论文 and 修改一下前馈(Fine Turing)

image-20240508192545250

预期的难点和挑战:

  • 分词
  • 中文的好一点的数据(这个好像Hugging Face 的官网上也有)
  • 论文part 的工作

相关论文:

链接:https://pan.baidu.com/s/1eeHn0hVB8HHyrHzWLZc-EQ?pwd=qooh
提取码:qooh
–来自百度网盘超级会员V5的分享

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/322052.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

音源分离|数据集|MUSDB18-HQ

一、说明 MUSDB18-HQ是MUSDB18数据集的未压缩版本。它由总共150首不同风格的完整歌曲组成&#xff0c;包括立体声混音和原始源&#xff0c;分为训练子集和测试子集。 其目的是作为设计和评估源分离算法的参考数据库。这种信号处理方法的目的是从一组混合物中估计一个或多个源&a…

2023年谷歌拒了228万应用,禁了33.3万账号,开发者们应如何应对2024的挑战?

谷歌在上周一公布了去年如何应对恶意应用和恶意行为。 报告指出&#xff0c;去年谷歌在Google Play平台上&#xff0c;通过不断升级安全系统、更新政策规定、运用先进的机器学习技术&#xff0c;以及严格把关应用审核流程&#xff0c;成功阻止了高达228万个不合规的应用程序上架…

2024牛客五一集训派对day2 Groundhog Looking Dowdy 个人解题思路

前言&#xff1a; 被实验室教练要求要打的这次五一牛客的训练赛&#xff0c;这些区域赛难度的题对于大一的我来说难度实在是太高了&#xff0c;我和我的队友只写了一些非常简单的签到题&#xff0c;其他题目都没怎么看&#xff08;我们太弱了&#xff09;&#xff0c;但我可以分…

使用Gradio搭建聊天UI实现质谱AI智能问答

使用Gradio搭建聊天UI实现质谱AI智能问答 一、调用智谱 AI API二、使用Gradio搭建聊天UI三、将流式处理添加到交互式聊天机器人 一、调用智谱 AI API 1、获取api_key 智谱AI开放平台网址&#xff1a; https://open.bigmodel.cn/overview 2、安装库pip install zhipuai 3、执…

[笔试训练](十六)

目录 046:字符串替换 047:神奇数 048:DNA序列 046:字符串替换 字符串替换_牛客题霸_牛客网 (nowcoder.com) 题目&#xff1a; 题解&#xff1a; 简单模拟题~ class StringFormat { public:string formatString(string str, int n, vector<char> arg, int m) {strin…

API开发的必备神器:华为云CodeArts API实用体验入门篇

今天我想给大家推荐一款API全生命周期研发与管理工具&#xff1a;华为云CodeArts API。 作为互联网软件的开发者&#xff0c;在软件研发的过程中&#xff0c;API的开发、调试、测试是必不可少的。之前我使用的是Postman这类工具来辅助开发&#xff0c; Postman在接口调试方面确…

WPF TextBox文本框 输入提示

思路 Grid标签里面创建Label和TextBox&#xff0c;这是一个整体。 TextBox 为空显示 Label OR TextBox 不为空隐藏 Label 。 注意 两个标签的前后顺序。 TextBox文本的背景颜色设置为透明&#xff0c;不然会无法看到 Label 内容。 ElementNametxtStoreName&#xff1a;指定…

Microsoft Universal Print 与 SAP 集成教程

引言 从 SAP 环境打印是许多客户的要求。例如数据列表打印、批量打印或标签打印。此类生产和批量打印方案通常使用专用硬件、驱动程序和打印解决方案来解决。 Microsoft Universal Print 是一种基于云的打印解决方案&#xff0c;它允许组织以集中化的方式管理打印机和打印机驱…

Shell变成规范与变量

目录 1. Shell脚本 1.1 Shell脚本概述 1.2 Shell的作用 1.3 Shell脚本的构成 2. 重定向与管道操作 2.1 交互式硬件设备 ​ 2.2 重定向操作 3. shell变量 3.1 自定义变量 3.2 变量的作用范围​编辑 3.3 整数变量的运算 4. 环境变量 4.1 特殊的Shell变量 4.2 只读变…

【Flask 系统教程 5】视图进阶

类视图 在 Flask 中&#xff0c;除了使用函数视图外&#xff0c;你还可以使用类视图来处理请求。类视图提供了一种更为结构化和面向对象的方式来编写视图函数&#xff0c;使得代码组织更清晰&#xff0c;并且提供了更多的灵活性和可扩展性。 创建类视图 要创建一个类视图&am…

家用洗地机应该怎么选?哪个牌子好?市场上主流洗地机品牌推荐

洗地机的出现&#xff0c;让越来越多的家庭享受清洁的过程&#xff0c;给人们腾出来更多的时间陪伴家人和休息。但是在选购一台洗地机前&#xff0c;大家多多少少肯定有些疑问&#xff0c;洗地机到底实不实用&#xff1f;好不好用&#xff1f;能扫干净吗&#xff1f;还有哪些好…

什么样的行业适合做私域?

私域营销适用于各种行业&#xff0c;但以下几个行业尤其适合进行私域营销&#xff1a; 1、零售行业&#xff1a;私域营销可以帮助零售企业建立与顾客的直接联系&#xff0c;提高顾客忠诚度和复购率。通过私域营销&#xff0c;零售企业可以进行个性化推荐、定制化服务&#xff…

Konga域名配置多个路由

云原生API网关-Kong部署与konga基本使用 Nginx server{listen 443 ssl;location / {proxy_pass http://127.0.0.1:8100;}location /openApi {proxy_pass http://172.31.233.35:7100/openApi;} } Kong {"id": "f880b21c-f7e0-43d7-a2a9-221fe86d9231&q…

vue视图不刷新强制更新数据this.$forceUpdate()

在vue中&#xff0c;更新视图数据&#xff0c;不刷新页面&#xff0c;需要强制更新数据才可以 前言 在对数据就行添加和删除时&#xff0c;发现页面视图不更新&#xff0c;排除发现需要强制更新才可以 点击添加或删除&#xff0c;新增数据和删除就行&#xff0c;但在不使用fo…

指定地区|CSC高级研究学者赴澳大利亚访学交流

CSC高级研究学者均是正高或博导级的&#xff0c;学术背景较强&#xff0c;多数能DIY联系到国外合作机构。但也有些申请者因指定地域或学校&#xff0c;或须在短期内获取邀请函故而求助于我们。本案例D教授就指定澳大利亚的墨尔本地区&#xff0c;我们最终用维多利亚大学的邀请函…

智能化采购管理系统助力光伏行业提高效率

光伏行业是指太阳能电池板的制造、安装和维护等相关产业&#xff0c;是新能源领域的重要组成部分。近年来&#xff0c;随着全球对于环保和可持续发展的重视&#xff0c;光伏行业进入全球化和智能化的新阶段。光伏企业开始加强国际合作&#xff0c;推广智能化技术&#xff0c;提…

vue3+ts+vant选择器选中文字效果

所需要的样式: 选中某个选项后文字有放大和改变颜色的效果 主要就是在van-picker上加class, 给对应的style样式即可 <van-pickerclass"custom-picker":title"pickerData.titleText"v-if"pickerData.ispicker"show-toolbar:columns"col…

数据结构——排序算法分析与总结

一、插入排序 1、直接插入排序 核心思想&#xff1a;把后一个数插入到前面的有序区间&#xff0c;使得整体有序 思路&#xff1a;先取出数组中第一个值&#xff0c;然后再用tmp逐渐取出数组后面的值&#xff0c;与前面的值进行比较&#xff0c;假如我们进行的是升序排序&…

代谢组数据分析七:从质谱样本制备到MaxQuant搜库

前言 LC-MS/MS Liquid Chromatography-Mass Spectrometry&#xff08;LC-MS/MS &#xff0c;液相色谱-质谱串联&#xff09;可用于残留化合物检测、有机小分子检测、鉴定和定量污染物以及在医药和食品领域添加剂检测和生物小分子等检测。 LC-MS/MS一般包含五个步骤&#xff…

熟悉Redis吗,那Redis的过期键删除策略是什么

对于Redis&#xff0c;我们业务开发一般都只关心Redis键值对的查询、修改操作&#xff0c;可能因为懒或者只想能用就行&#xff0c;呵呵。很少关心键值对存储在什么地方、键值对过期了会怎么样、Redis有没什么策略处理过期的键、Redis处理过期键又有什么作用&#xff1f;但这些…