如何为 BERT 准备文本 - 出现错误

How to prepare text for BERT - getting error

我正在尝试学习用于文本分类的 BERT。我在为使用 BERT 准备数据时发现了一些问题。

根据我的数据集,我将情绪和评论分离为:

X = df['sentiments']
y = df['reviews'] #it contains four different class of reviews

接下来,

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
train_encodings = tokenizer(X_train, truncation=True, padding=True, max_length=512) 

这是我出错的地方:

ValueError                                Traceback (most recent call last)
<ipython-input-70-22714fcf7991> in <module>()
----> 1 train_encodings = tokenizer(X_train, truncation=True, padding=True, max_length=max_length)
      2 #valid_encodings = tokenizer(valid_texts, truncation=True, padding=True, max_length=max_length)

/usr/local/lib/python3.7/dist-packages/transformers/tokenization_utils_base.py in __call__(self, text, text_pair, add_special_tokens, padding, truncation, max_length, stride, is_split_into_words, pad_to_multiple_of, return_tensors, return_token_type_ids, return_attention_mask, return_overflowing_tokens, return_special_tokens_mask, return_offsets_mapping, return_length, verbose, **kwargs)
   2261         if not _is_valid_text_input(text):
   2262             raise ValueError(
-> 2263                 "text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
   2264                 "or `List[List[str]]` (batch of pretokenized examples)."
   2265             )

ValueError: text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) or `List[List[str]]` (batch of pretokenized examples).

当我尝试将 X 转换为列表并使用它时,出现另一个错误:

TypeError: TextEncodeInput must be Union[TextInputSequence, Tuple[InputSequence, InputSequence]]

谁能解释一下问题出在哪里?之前我遵循了一个关于 20 个新闻数据集的教程并且它有效。但是现在用在别的项目上,用不了,心里很难过

谢谢。

错误是因为,您的 X = df['sentiments']y = df['reviews'] 行,其中您的 X 和 y 仍然是数据框列(或数据框系列),而不是列表。更改它们的简单方法是:

X = df['sentiments'].valuesy = df['reviews'].values

which returns numpy 数组,并且有效。如果不是可以使用

进一步转换为python列表

X = df['sentiments'].values.tolist()y = df['reviews'].values.tolist()