BertModel变压器输出字符串而不是张量

我正在关注这个使用 BERT 和Huggingface库编写情感分析分类器的教程,我有一个非常奇怪的行为。当使用示例文本尝试 BERT 模型时,我得到一个字符串而不是隐藏状态。这是我正在使用的代码:

import transformers
from transformers import BertModel, BertTokenizer

print(transformers.__version__)

PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
PATH_OF_CACHE = "/home/mwon/data-mwon/paperChega/src_classificador/data/hugingface"

tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)

sample_txt = 'When was I last outside? I am stuck at home for 2 weeks.'

encoding_sample = tokenizer.encode_plus(
  sample_txt,
  max_length=32,
  add_special_tokens=True, # Add '[CLS]' and '[SEP]'
  return_token_type_ids=False,
  padding=True,
  truncation = True,
  return_attention_mask=True,
  return_tensors='pt',  # Return PyTorch tensors
)

bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)


last_hidden_state, pooled_output = bert_model(
  encoding_sample['input_ids'],
  encoding_sample['attention_mask']
)

print([last_hidden_state,pooled_output])

输出:

4.0.0
['last_hidden_state', 'pooler_output']
 

回答

虽然Aakash的回答提供了问题的解决方案,但并没有解释问题。由于转换器库的 3.X 版本之一,模型不再返回元组,而是返回特定的输出对象:

o = bert_model(
    encoding_sample['input_ids'],
    encoding_sample['attention_mask']
)
print(type(o))
print(o.keys())
o = ber
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])

输出:

您可以通过添加return_dict=False以获取元组来返回到之前的行为:

输出:

我不建议这样做,因为现在选择输出的特定部分而不使用文档是明确的,如下例所示:

<class 'tuple'>

输出:


I am a tuple with 4 elements. You do not know what each element presents without checking the documentation
I am a cool object and you can acces my elements with o.last_hidden_state,  o["last_hidden_state"] or even o[0]. My keys are; odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states', 'attentions']) 
以上是BertModel变压器输出字符串而不是张量的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>