浅谈feature-based 和 fine-tune

feature-based 和 fine-tune是NLP方向使用预训练模型时常用的两种方式,所以简单总结下。

Feature-based

Feature-based指在使用时,并不直接使用模型本身,而是利用模型产生的结果,即LM embedding,通过预训练的模型处理数据得到额外的特征,引入到要训练的模型中。

例如,在文本分类、序列标注等任务中,对输入的词进行编码得到词的embedding时,

对于静态词向量(word2vec, glove)就是使用查表的方式,每个词根据word2vec或者glove甚至是最原始的one-hot方式,得到的静态词向量,一个词对应一个200或者300维的向量表示,在下游任务中继续更新。所以说其实word2vec就是最原始的预训练语言模型,先用一批数据训练得到一批词的静态词向量。

而动态词向量(elmo和bert)也是一样,可以直接拿下游训练的数据,输入训练好的编码器encoder,然后得到每个词的embedding,也可以拿某层的hidden state输出当做额外的特征,引入到要训练的模型中,在下游任务中只训练这些输出的线性组合(w1 * h1 + w2 * h2 + w3 * h3 …)中的w,而h是不变的。
这样的做法一个明显的缺点就是占用存储太大了,毕竟要把所有的特征都保存一下。

  • 静态词向量指训练以后,不发生改变了,也就是一个词只能唯一确定的向量和它对应,无法解决一词多义问题
  • 动态词向量指同一个词的embedding会因为不同的上下文而发生变化

feature-based方法包括两步:

  1. 首先在大的语料A上无监督地训练语言模型,训练完毕得到语言模型
  2. 然后构造task-specific model例如序列标注模型,采用有标记的语料B来有监督地训练task-sepcific model,将语言模型的参数固定,语料B的训练数据经过语言模型得到LM embedding,作为task-specific model的额外特征

fine-tune

Fine-tune 方法会根据下游特定的任务,在原来的模型上面进行一些修改,使得最后输出是当前任务需要的,然后在新的语料上重新训练来进行fine-tune。这些修改一般是在模型的最后一层,或者在现有的网络后添加一个网络结构用于匹配下游的各种任务。

GPT1 GPT2 就采用了Fine-tune 方法,GPT3得益于海量的与训练样本和庞大的网络参数,不在需要 fine-tune过程;

BERT论文采用了LM + fine-tuning的方法,同时也讨论了BERT + task-specific model的方法,例如情感分析任务,将数据输入bert模型,将最后的输出取得第一个token的输出,传入一个softmax层,得到一个分类的结果,所以其实就是在最后加了一层softmax。

但是这种方式的话很明显占用资源更大,因为要重新训练,实现的时候又会有各种各样的问题,所以还是需要实践来完善。

fine-tune分为两个步骤:

  1. 构造语言模型,采用大的语料A来训练语言模型
  2. 在语言模型基础上增加少量神经网络层来完成specific task例如序列标注、分类等,然后采用有标记的语料B来有监督地训练模型,这个过程中语言模型的参数并不固定,依然是trainable variables.

使用BERT应用于不同的下游任务例子,具体的如下:

  • 对于情感分析等单句分类任务,可以直接输入单个句子(不需要[SEP]分隔双句),将[CLS]的输出直接输入到分类器进行分类
  • 对于句子对任务(句子关系判断任务),需要用[SEP]分隔两个句子输入到模型中,然后同样仅须将[CLS]的输出送到分类器进行分类

  • 对于问答任务,将问题与答案拼接输入到BERT模型中,然后将答案位置的输出向量进行二分类并在句子方向上进行softmax(只需预测开始和结束位置即可)

  • 对于命名实体识别任务,对每个位置的输出进行分类即可,如果将每个位置的输出作为特征输入到CRF将取得更好的效果。

  • 对于常规分类任务中,需要在 Transformer 的输出之上加一个分类层.

参考资料:
feature-based 和 fine-tune
#深入理解# NLP 中的 Feature-based 和 Fine-tune 两种学习方法
论文解读:BERT模型及fine-tuning

### Transformer Model Jupyter Notebook Examples and Tutorials For those interested in exploring the capabilities of Transformer models through practical implementation, several resources provide comprehensive Jupyter Notebook examples and tutorials that cover various aspects of these powerful architectures. #### Example 1: Hugging Face Transformers Library Tutorial A widely used library for implementing Transformer-based models is provided by Hugging Face. The official documentation includes a detailed tutorial on how to fine-tune pre-trained models like BERT, DistilBERT, RoBERTa, etc., using PyTorch or TensorFlow frameworks within a Jupyter environment[^1]. ```python from transformers import AutoModelForMaskedLM, AutoTokenizer import torch model_name = "distilbert-base-uncased" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForMaskedLM.from_pretrained(model_name) text = "[MASK] was a great day." inputs = tokenizer(text, return_tensors="pt") with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits predicted_token_id = logits.argmax(dim=-1).squeeze()[1].item() print(tokenizer.decode(predicted_token_id)) ``` This code snippet demonstrates loading a pre-trained DistilBERT model along with its corresponding tokenizer from the Hugging Face Hub, processing an input sentence containing masked tokens, performing inference, and finally decoding predictions back into readable text form. #### Example 2: Implementing Custom Text Classification Pipeline Using Scikit-Learn and Keras Another approach involves integrating traditional machine learning pipelines (such as scikit-learn) with deep learning components via libraries such as Keras/TensorFlow. This hybrid method allows leveraging both classical algorithms alongside modern neural networks when building NLP applications[^3]. ```python from sklearn.feature_extraction.text import CountVectorizer from keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense max_features = 5000 max_len = 100 vectorizer = CountVectorizer(max_features=max_features) X_train_counts = vectorizer.fit_transform(X_train).toarray() vocab_size = len(vectorizer.vocabulary_) + 1 embedding_dim = 100 model = Sequential([ Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_len), LSTM(units=64), Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(pad_sequences(X_train_counts), y_train, epochs=10, batch_size=32, validation_split=0.2) ``` In this example, `CountVectorizer` converts raw texts into numerical feature vectors suitable for training simple classifiers while maintaining compatibility with more complex sequential data structures required by recurrent layers found inside LSTMs. --related questions-- 1. What are some best practices for preparing datasets specifically designed for transformer-based models? 2. How does one evaluate the performance of different types of embedding techniques utilized during preprocessing stages prior to feeding inputs into transformer architectures? 3. Can you explain what hyperparameters should be tuned carefully when working with large-scale language modeling tasks involving transformers?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值