PyTorch BERT TypeError: forward () получил неожиданный аргумент ключевого слова «метки» - PullRequest
0 голосов
/ 18 октября 2019

Обучение модели BERT с использованием преобразователей PyTorch (после учебника здесь ).

Следование утверждению в учебнике

loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)

приводит к

TypeError: forward() got an unexpected keyword argument 'labels'

Вот полная ошибка,

TypeError                                 Traceback (most recent call last)
<ipython-input-53-56aa2f57dcaf> in <module>
     26         optimizer.zero_grad()
     27         # Forward pass
---> 28         loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
     29         train_loss_set.append(loss.item())
     30         # Backward pass

~/anaconda3/envs/systreviewclassifi/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    539             result = self._slow_forward(*input, **kwargs)
    540         else:
--> 541             result = self.forward(*input, **kwargs)
    542         for hook in self._forward_hooks.values():
    543             hook_result = hook(self, input, result)

TypeError: forward() got an unexpected keyword argument 'labels'

Кажется, я не могу понять, какой аргумент ожидает функция forward ().

Есть похожая проблема здесь , но я все еще не понимаю, в чем заключается решение.

Системная информация:

  • ОС: Ubuntu 16.04 LTS
  • Версия Python: 3.6. x
  • Версия горелки: 1.3.0
  • Версия Torch Vision: 0.4.1
  • Версия трансформаторов PyTorch: 1.2.0

1 Ответ

2 голосов
/ 18 октября 2019

Насколько я знаю, BertModel не принимает метки в функции forward(). Проверьте параметры функции forward .

Я подозреваю, что вы пытаетесь настроить BertModel для задачи классификации последовательности, и API предоставляет класс для этого BertForSequenceClassification . Как видно из определения функции forward ():

def forward(self, input_ids, attention_mask=None, token_type_ids=None,
            position_ids=None, head_mask=None, labels=None):

Обратите внимание, что метод forward () возвращает следующее.

Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Classification (or regression if config.num_labels==1) loss.
        **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``
            Classification (or regression if config.num_labels==1) scores (before SoftMax).
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...