使用 BERT 和 Keras 的神经网络进行文本分类

Posted

技术标签:

【中文标题】使用 BERT 和 Keras 的神经网络进行文本分类【英文标题】:Using BERT and Keras's neural network for text classification 【发布时间】:2021-05-08 02:18:27 【问题描述】:

我正在尝试使用 BERT 运行二进制监督文本分类任务,但我不知道该怎么做。 我尝试使用 Hugging Face (????) 库运行 BERT,但我不知道如何处理该过程的输出。

经过大量互联网搜索后,我最终获得了以下课程(根据https://towardsdatascience.com/build-a-bert-sci-kit-transformer-59d60ddd54a5):

class BertTransformer(BaseEstimator, TransformerMixin):
    def __init__(self):
        self.tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
        self.model = BertModel.from_pretrained("bert-base-uncased")
        self.model.eval()
        self.embedding_func = lambda x: x[0][:, 0, :].squeeze()

    def _tokenize(self, text: str):
        # Tokenize the text with the provided tokenizer
        tokenized_text = self.tokenizer.encode_plus(text,
                                                    add_special_tokens=True,
                                                    truncation=True
                                                    )["input_ids"]

        # Create an attention mask telling BERT to use all words
        attention_mask = [1] * len(tokenized_text)

        # bert takes in a batch so we need to unsqueeze the rows
        return (
            torch.tensor(tokenized_text).unsqueeze(0),
            torch.tensor(attention_mask).unsqueeze(0),
        )

    def _tokenize_and_predict(self, text: str) -> torch.tensor:
        tokenized, attention_mask = self._tokenize(text)

        embeddings = self.model(tokenized, attention_mask)
        return self.embedding_func(embeddings)

    def transform(self, text: List[str]):
        if isinstance(text, pd.Series):
            text = text.tolist()

        with torch.no_grad():
            return torch.stack([self._tokenize_and_predict(string) for string in text])

    def fit(self, X, y=None):
        return self

    这个类适合在 Sikict-Learn 中使用,这对我有好处,但我也想用 Keras 的深度学习模型来运行它。如何使用 Keras 的神经网络(如 RNN 和 CNN)实现这项工作?

    据我了解,上述代码仅使用 CLS 令牌,而不是所有令牌。我不知道这样行不行。也许我应该使用所有这些?如果是这样,我该怎么做?

任何帮助将不胜感激。

【问题讨论】:

您的代码正在使用 pytorch,并且您的问题上有 tensorflow 和 keras 标签 考虑使用BertForSequenceClassification 类。另外,本教程似乎不错:medium.com/@knswamy/… 【参考方案1】:

我不确定您所说的流程输出是什么意思。如果您想使用该模型进行预测,您可以使用类似下面的代码来执行此操作。在这个库中,可能有一些关于如何使用基于预训练模型的预测的提示,lazy-text-predict 它也可以帮助您实现文本分类器。

text='my text to classify'
model=BertForSequenceClassification.from_pretrained('/content/bert-base-uncased_model')
tokenizer=BertTokenizerFast.from_pretrained('bert-base-uncased')
text_classification= transformers.pipeline('sentiment-analysis',
                                            model=model, 
                                            tokenizer=tokenizer)
y=text_classification(text)[0]
print(y)

【讨论】:

以上是关于使用 BERT 和 Keras 的神经网络进行文本分类的主要内容,如果未能解决你的问题,请参考以下文章

[Python人工智能] 三十二.Bert模型 Keras-bert基本用法及预训练模型

[Python人工智能] 三十四.Bert模型 keras-bert库构建Bert模型实现微博情感分析

ImportError: cannot import name 'Tokenizer' from 'keras_bert'

项目小结训练BERT模型加入到深度学习网络层中——keras_bert库使用填坑指南

项目小结训练BERT模型加入到深度学习网络层中——keras_bert库使用填坑指南

BERT实战——基于Keras