python 拥抱面Transformer型号:KeyError:BERT模型训练开始时的“input_ids”消息

2ledvvac  于 2023-10-15  发布在  Python
关注(0)|答案(1)|浏览(192)

在使用Huggingface Transformer库的最后一步中,当我为掩码语言建模任务微调BERT语言模型时,我遇到了一个bug。我期待着微调它的领域金融语料库,模型还没有被训练。然而,当我调用模型进行训练时,我得到以下错误消息:KeyError:'input_ids'.下面是我的代码和步骤。任何见解都是赞赏的!
首先,我从一个pandas框架创建了一个数据集对象,该框架又从一个csv文件创建,该文件具有一列多行文本:

unlabelled_dataset = Dataset.from_pandas(unlabelled)

然后,我用下面的代码对数据集进行了标记:

tokenizerBERT = BertTokenizerFast.from_pretrained('bert-base-uncased')  #BERT model tokenization & check
tokenizerBERT(unlabelled_dataset['paragraphs'], padding=True, truncation=True)
tokenizerBERT.save_pretrained('tokenizers/pytorch/labelled/BERT/')

第三,我按照指示创建了一个数据整理器:

data_collator_BERT = DataCollatorForLanguageModeling(tokenizer=tokenizerBERT, mlm=True, mlm_probability=0.15)

接下来,我从_pretrained中选择我的模型,以获得迁移学习的好处:

model_BERT = BertForMaskedLM.from_pretrained("bert-base-uncased")

接下来,我将我的训练参数传递给Transformer训练器并初始化:

training_args_BERT = TrainingArguments(
    output_dir="./BERT",
    num_train_epochs=10,
    evaluation_strategy='steps',
    warmup_steps=10000,
    weight_decay=0.01,
    per_gpu_train_batch_size=64,    
)

trainer_BERT = Trainer(
    model=model_BERT,
    args=training_args_BERT,
    data_collator=data_collator_BERT,
    train_dataset=unlabelled_dataset,
)

最后,我调用模型进行训练,并得到错误KeyError:'input_id'

trainer_BERT.train()

对于如何调试这种训练模型的方法有什么见解吗?
下面提供的是收到的确切错误消息:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-83b7063dea0b> in <module>
----> 1 trainer_BERT.train()
      2 trainer.save_model("./models/royalBERT")

~/anaconda3/lib/python3.7/site-packages/transformers/trainer.py in train(self, model_path, trial)
    755             self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control)
    756 
--> 757             for step, inputs in enumerate(epoch_iterator):
    758 
    759                 # Skip past any already trained steps if resuming training

~/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
    361 
    362     def __next__(self):
--> 363         data = self._next_data()
    364         self._num_yielded += 1
    365         if self._dataset_kind == _DatasetKind.Iterable and \

~/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _next_data(self)
    401     def _next_data(self):
    402         index = self._next_index()  # may raise StopIteration
--> 403         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    404         if self._pin_memory:
    405             data = _utils.pin_memory.pin_memory(data)

~/anaconda3/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py in fetch(self, possibly_batched_index)
     45         else:
     46             data = self.dataset[possibly_batched_index]
---> 47         return self.collate_fn(data)

~/anaconda3/lib/python3.7/site-packages/transformers/data/data_collator.py in __call__(self, examples)
    193     ) -> Dict[str, torch.Tensor]:
    194         if isinstance(examples[0], (dict, BatchEncoding)):
--> 195             examples = [e["input_ids"] for e in examples]
    196         batch = self._tensorize_batch(examples)
    197         if self.mlm:

~/anaconda3/lib/python3.7/site-packages/transformers/data/data_collator.py in <listcomp>(.0)
    193     ) -> Dict[str, torch.Tensor]:
    194         if isinstance(examples[0], (dict, BatchEncoding)):
--> 195             examples = [e["input_ids"] for e in examples]
    196         batch = self._tensorize_batch(examples)
    197         if self.mlm:

KeyError: 'input_ids'
v64noz0r

v64noz0r1#

虽然tokenizer是通过DataCollator传递的,但我认为我们必须对数据进行tokenization:
因此,我们需要对数据进行标记化,如下所示:

train_dataset = tokenizer.encode(unlabeled_data, add_special_tokens=True, return_tensors="pt")
trainer_BERT = Trainer(
    model=model_BERT,
    args=training_args_BERT,
    data_collator=data_collator_BERT,
    train_dataset=train_dataset,
)

相关问题