例如,在类BertForSequenceClassificationdefinition中,只有一个Linear层用于分类器。如果只用一个Linear layer,不就是对pooled_out做线性投影吗?这样的分类器会产生好的预测吗?为什么不使用多个线性层? Transformers 是否提供使用多个线性层作为分类头的选项?
我看了其他几个班级。它们都使用单个线性层作为分类头。
由于下游场景无限多,对于一个任务没有万能的head,transformers库只增加了一个足以完成任务的head。您需要尝试使用自己的数据和不同的架构,以防性能达不到您的预期。
该库与 PyTorch 完全兼容,您可以将每个模型的基类用作您自己的 NN 中的模块:
import torch
import torch.nn as nn
from transformers import BertModel, BertTokenizer
class MyOwnBert(nn.Module):
def __init__(self, model_id, num_labels):
super(MyOwnBert, self).__init__()
self.bert = BertModel.from_pretrained(model_id)
self.my_fancy_outputLayer = nn.Sequential(
nn.GELU(),
nn.Dropout(0.1),
nn.Linear(self.bert.config.hidden_size, self.bert.config.hidden_size),
nn.GELU(),
nn.Linear(self.bert.config.hidden_size, num_labels),
)
def forward(
self,
input_ids = None,
attention_mask = None,
token_type_ids = None,
position_ids = None,
labels = None,
):
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
)
pooled_output = outputs.pooler_output
logits = self.my_fancy_outputLayer(pooled_output)
return logits
model_id = "bert-base-uncased"
t = BertTokenizer.from_pretrained(model_id)
m = MyOwnBert(model_id, 4)
m(**t("this is just an example", return_tensors="pt"))
输出:
tensor([[ 0.0291, -0.0370, 0.0255, 0.0234]], grad_fn=<AddmmBackward0>)