我正在处理文本分类问题(例如情感分析),我需要将文本字符串分类为五个类别之一。
我刚开始在 PyTorch 中使用 Huggingface Transformer 包和 BERT。我需要的是一个顶部带有 softmax 层的分类器,以便我可以进行 5 向分类。令人困惑的是,Transformer 包中似乎有两个相关选项: BertForSequenceClassification 和 BertForMultipleChoice 。
我的 5 向分类任务应该使用哪一种?他们的适当用例是什么?
BertForSequenceClassification 的文档根本没有提到 softmax,尽管它确实提到了交叉熵。我不确定这个类是否仅用于 2 类分类(即逻辑回归)。
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
- labels (torch.LongTensor of shape (batch_size,), optional, defaults to None) – Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).
BertForMultipleChoice 的文档中提到了softmax,但是标签的描述方式,听起来这个类是针对多标签分类的(即多标签的二元分类)。
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks.
- labels (torch.LongTensor of shape (batch_size,), optional, defaults to None) – Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices] where num_choices is the size of the second dimension of the input tensors.
感谢您的任何帮助。
最佳答案
这个问题的答案在于(诚然非常简短的)任务是关于什么的描述:
[
BertForMultipleChoice
] [...], e.g. for RocStories/SWAG tasks.
当查看 paper for SWAG 时,任务似乎实际上是在学习从不同的选项中进行选择。这与您的“经典”分类任务形成对比,其中“选择”(即类别)不会因您的样本而异,这正是
BertForSequenceClassification
的用途。实际上,通过更改配置中的
BertForSequenceClassification
参数,这两种变体都可以用于任意数量的类(在 BertForMultipleChoice
的情况下)和选择(对于 labels
)。但是,由于您似乎正在处理“经典分类”的情况,我建议使用 BertForSequenceClassification
模型。很快解决
BertForSequenceClassification
中缺少的 Softmax :由于分类任务可以计算独立于样本的类别的损失(与多项选择不同,您的分布正在变化),这允许您使用交叉熵损失,它在反向传播步骤中考虑 Softmax对于 increased numerical stability 。
关于python - BertForSequenceClassification 与用于句子多类分类的 BertForMultipleChoice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610280/