如何在词嵌入模型BERT上使用自己的语料库

How to use my own corpus on word embedding model BERT

我正在尝试使用来自 google 的词嵌入模型 BERT 创建一个问答模型。我是新手,真的很想用我自己的语料库进行训练。起初我使用了 huggingface site 中的一个例子并且效果很好:

from transformers import pipeline

qa_pipeline = pipeline(
    "question-answering",
    model="henryk/bert-base-multilingual-cased-finetuned-dutch-squad2",
    tokenizer="henryk/bert-base-multilingual-cased-finetuned-dutch-squad2"
)

qa_pipeline({
    'context': "Amsterdam is de hoofdstad en de dichtstbevolkte stad van Nederland.",
    'question': "Wat is de hoofdstad van Nederland?"})

输出

> {'answer': 'Amsterdam', 'end': 9, 'score': 0.825619101524353, 'start': 0}

因此,我尝试创建一个 .txt 文件来测试是否可以将上下文参数中的句子与 .txt 文件中的完全相同的句子互换。

with open('test.txt') as f:
    lines = f.readlines()

qa_pipeline = pipeline(
    "question-answering",
    model="henryk/bert-base-multilingual-cased-finetuned-dutch-squad2",
    tokenizer="henryk/bert-base-multilingual-cased-finetuned-dutch-squad2"
)

qa_pipeline({
    'context': lines,
    'question': "Wat is de hoofdstad van Nederland?"})

但这给了我以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-2bae0ecad43e> in <module>()
     10 qa_pipeline({
     11     'context': lines,
---> 12     'question': "Wat is de hoofdstad van Nederland?"})

5 frames
/usr/local/lib/python3.6/dist-packages/transformers/data/processors/squad.py in _is_whitespace(c)
     84 
     85 def _is_whitespace(c):
---> 86     if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
     87         return True
     88     return False

TypeError: ord() expected a character, but string of length 66 found

我只是在试验读取和使用 .txt 文件的方法,但我似乎没有找到不同的解决方案。我对 huggingface pipeline() 函数做了一些研究,这是关于问题和上下文参数的内容:

知道了!解决方案真的很简单。我假设变量 'lines' 已经是一个 str 但事实并非如此。只需转换为字符串,问答模型就接受了我的 test.txt 文件。

所以来自:

with open('test.txt') as f:
    lines = f.readlines()

至:

with open('test.txt') as f:
    lines = str(f.readlines())