我正在尝试解决多类文本分类问题。由于我项目的特定要求,我尝试使用skorch(https://skorch.readthedocs.io/en/stable/index.html)来为sklearn管道包装pytorch。我想做的是用我的数据集微调Huggingface(https://huggingface.co)的BERT的预训练版本。据我所知,我一直尝试按照skorch的指示输入数据,构建模型等。在训练期间,火车损耗一直下降到第8个时期,在此期间它开始波动。验证损失从一开始就增加,并且验证精度保持恒定为零。我的管道设置是
from sklearn.pipeline import Pipeline
pipeline = Pipeline(
[
("tokenizer", Tokenizer()),
("classifier", _get_new_transformer())
]
其中,我正在使用令牌生成器类来预处理我的数据集,将其令牌化为BERT并创建注意掩码。看起来像这样
import torch
from transformers import AutoTokenizer, AutoModel
from torch import nn
import torch.nn.functional as F
from sklearn.base import BaseEstimator, TransformerMixin
from tqdm import tqdm
import numpy as np
class Tokenizer(BaseEstimator, TransformerMixin):
def __init__(self):
super(Tokenizer, self).__init__()
self.tokenizer = AutoTokenizer.from_pretrained(/path/to/model)
def _tokenize(self, X, y=None):
tokenized = self.tokenizer.encode_plus(X, max_length=20, add_special_tokens=True, pad_to_max_length=True)
tokenized_text = tokenized['input_ids']
attention_mask = tokenized['attention_mask']
return np.array(tokenized_text), np.array(attention_mask)
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
word_tokens, attention_tokens = np.array([self._tokenize(string)[0] for string in tqdm(X)]), \
np.array([self._tokenize(string)[1] for string in tqdm(X)])
X = word_tokens, attention_tokens
return X
def fit_transform(self, X, y=None, **fit_params):
self = self.fit(X, y)
return self.transform(X, y)
然后初始化要微调为
的模型 class Transformer(nn.Module):
def __init__(self, num_labels=213, dropout_proba=.1):
super(Transformer, self).__init__()
self.num_labels = num_labels
self.model = AutoModel.from_pretrained(/path/to/model)
self.dropout = torch.nn.Dropout(dropout_proba)
self.classifier = torch.nn.Linear(768, num_labels)
def forward(self, X, **kwargs):
X_tokenized, attention_mask = torch.stack([x.unsqueeze(0) for x in X[0]]),\
torch.stack([x.unsqueeze(0) for x in X[1]])
_, X = self.model(X_tokenized.squeeze(), attention_mask.squeeze())
X = F.relu(X)
X = self.dropout(X)
X = self.classifier(X)
return X
我初始化模型并使用skorch创建分类器,如下所示
from skorch import NeuralNetClassifier
from skorch.dataset import CVSplit
from skorch.callbacks import ProgressBar
import torch
from transformers import AdamW
def _get_new_transformer() -> NeuralNetClassifier:
transformer = Transformer()
net = NeuralNetClassifier(
transformer,
lr=2e-5,
max_epochs=10,
criterion=torch.nn.CrossEntropyLoss,
optimizer=AdamW,
callbacks=[ProgressBar(postfix_keys=['train_loss', 'valid_loss'])],
train_split=CVSplit(cv=2, random_state=0)
)
return net
我会像这样
pipeline.fit(X=dataset.training_samples, y=dataset.training_labels)
根据pytorch的要求,我的训练样本是字符串列表,标签是包含每个类的索引的数组。
这是发生的情况的一个示例
我试图只训练完全连接的层,而不是BERT,但是我又遇到了同样的问题。在训练过程之后,我还测试了火车的准确性,仅为0.16%。如果您对解决问题有任何建议或见解,我将不胜感激!我对skorch很陌生,但对pytorch不太满意,我相信我缺少一些非常简单的东西。提前非常感谢您!