資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

機器之心發表於2017-07-29

今年 4 月,史丹佛大學和 Facebook 人工智慧研究所在 arXiv 釋出了一個基於維基百科的開放域問題問答研究 DrQA。近日,Facebook 在 GitHub 上開源了這個系統的程式碼,FAIR 主管 Yann LeCun 在社交網路也為這次開源做了宣傳。據悉,該研究也將出現在 7 月 30 日舉行的 ACL 2017 大會上。


論文地址:https://arxiv.org/abs/1704.00051

開源地址:https://github.com/facebookresearch/DrQA

Yann LeCun 的推薦語:

DrQA 是一個開放域的問答系統。向 DrQA 系統輸入一段文字,然後提一個答案能在該文字中找到的問題,那麼 DrQA 就能給出這個問題的答案。程式碼相關的論文將在 ACL 發表。向該團隊致敬:FAIR 研究工程師 Adam Fisch、史丹佛博士實習生 Danqi Chen 和 FAIR 科學家 Jason Weston 和 Antoine Bordes。


大規模機器閱讀

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

DrQA 是一個用於開放域問答的閱讀理解系統。DrQA 特別針對的是被稱為「大規模機器閱讀(MRS:machine reading at scale)」的任務。在這種設定中,我們要在可能非常大的非結構化文件語料庫(可能並不冗餘)中搜尋問題的答案。因此這個系統必然要將文件檢索難題(尋找相關文件)與文字的機器理解(在這些文件中確定答案的範圍)結合到一起。

我們使用 DrQA 的實驗專注於回答事實性問題,同時僅使用維基百科作為文件的唯一知識源。維基百科是一個非常合適的大規模、豐富和詳細的資訊源。為了回答一個問題,系統必須首先檢索超過 500 萬篇文章中的少數幾篇可能相關的文章,然後再仔細地掃描它們以確認答案。

注意,DrQA 將維基百科看作是文章的一般集合,而並不依賴其內部的圖結構。因此 DrQA 可以直接被用於任何文件的集合,正如在文件檢索器(Document Retriever)的 README 中描述的那樣。

這個 repo 包含了程式碼、資料和用於處理和查詢維基百科的預訓練的模型,該模型如論文中描述的一樣,參閱後文「訓練後的模型與資料」一節。我們也列出了幾種用於評估的不同資料集,參見後文「問答資料集」一節。注意這項工作是在原始程式碼基礎上的重構版本,也更加有效。再生數(reproduction numbers)非常相似,但並不完全一樣。

快速上手:演示

安裝 DrQA 並下載我們的模型,然後開始問開放域問題吧!

執行 python scripts/pipeline/interactive.py 可進入互動式的會話。對於每一個問題,會返回其上面涉及的範圍和其來源的維基百科段落。

>>> process('What is question answering?')

Top Predictions:
+------+----------------------------------------------------------------------------------------------------------+--------------------+--------------+-----------+
| Rank |                                                  Answer                                                  |        Doc         | Answer Score | Doc Score |
+------+----------------------------------------------------------------------------------------------------------+--------------------+--------------+-----------+
|  1   | a computer science discipline within the fields of information retrieval and natural language processing | Question answering |    1917.8    |   327.89  |
+------+----------------------------------------------------------------------------------------------------------+--------------------+--------------+-----------+

Contexts:
[ Doc = Question answering ]
Question Answering (QA) is a computer science discipline within the fields of
information retrieval and natural language processing (NLP), which is
concerned with building systems that automatically answer questions posed by
humans in a natural language.
>>> process('What is the answer to life, the universe, and everything?')

Top Predictions:
+------+--------+---------------------------------------------------+--------------+-----------+
| Rank | Answer |                        Doc                        | Answer Score | Doc Score |
+------+--------+---------------------------------------------------+--------------+-----------+
|  1   |   42   | Phrases from The Hitchhiker's Guide to the Galaxy |    47242     |   141.26  |
+------+--------+---------------------------------------------------+--------------+-----------+

Contexts:
[ Doc = Phrases from The Hitchhiker's Guide to the Galaxy ]
The number 42 and the phrase, "Life, the universe, and everything" have
attained cult status on the Internet. "Life, the universe, and everything" is
a common name for the off-topic section of an Internet forum and the phrase is
invoked in similar ways to mean "anything at all". Many chatbots, when asked
about the meaning of life, will answer "42". Several online calculators are
also programmed with the Question. Google Calculator will give the result to
"the answer to life the universe and everything" as 42, as will Wolfram's
Computational Knowledge Engine. Similarly, DuckDuckGo also gives the result of
"the answer to the ultimate question of life, the universe and everything" as
42. In the online community Second Life, there is a section on a sim called
43. "42nd Life." It is devoted to this concept in the book series, and several
attempts at recreating Milliways, the Restaurant at the End of the Universe, were made.
>>> process('Who was the winning pitcher in the 1956 World Series?')

Top Predictions:
+------+------------+------------------+--------------+-----------+
| Rank |   Answer   |       Doc        | Answer Score | Doc Score |
+------+------------+------------------+--------------+-----------+
|  1   | Don Larsen | New York Yankees |  4.5059e+06  |   278.06  |
+------+------------+------------------+--------------+-----------+

Contexts:
[ Doc = New York Yankees ]
In 1954, the Yankees won over 100 games, but the Indians took the pennant with
an AL record 111 wins; 1954 was famously referred to as "The Year the Yankees
Lost the Pennant". In , the Dodgers finally beat the Yankees in the World
Series, after five previous Series losses to them, but the Yankees came back
strong the next year. On October 8, 1956, in Game Five of the 1956 World
Series against the Dodgers, pitcher Don Larsen threw the only perfect game in
World Series history, which remains the only perfect game in postseason play
and was the only no-hitter of any kind to be pitched in postseason play until
Roy Halladay pitched a no-hitter on October 6, 2010.

你自己試試看吧!當然,DrQA 可能會提供其它的事實,所以請享受這段旅程吧。

安裝 DrQA

DrQA 的設定很簡單!

DrQA 需要 Python 3.5 或更高版本,也需要安裝 PyTorch。它的其它依賴要求可參閱 requirements.txt 檔案。

執行以下命令克隆這個庫並安裝 DrQA:

git clone https://github.com/facebookresearch/DrQA.git
cd DrQA; pip install -r requirements.txt; python setup.py develop

注:requirements.txt 包含所有可能所需的軟體包的一個子集。根據你要執行的內容,你可能需要安裝其它軟體包(比如 spaCy)。

如果你要使用 CoreNLPTokenizer 或 SpacyTokenizer,你還需要分別下載 Stanford CoreNLP jar 包和 spaCy en 模型。如果你使用 Stanford CoreNLP,讓 jar 位於你的 Java CLASSPATH 環境變數中,或使用以下程式碼通過程式設計方式設定路徑:

import drqa.tokenizers
drqa.tokenizer.set_default('corenlp_classpath', '/your/corenlp/classpath/*')

重要:預設的 tokenizer 是 CoreNLP,所以你需要在 CLASSPATH 裡面有它,以執行 README 示例。

比如:export CLASSPATH=$CLASSPATH:/path/to/corenlp/download/*

為了方便,如果沒有給定模型引數,Document Reader、Retriever 和 Pipeline 模組將會嘗試載入預設模型。參閱下面內容下載這些模型。

訓練後的模型與資料

要下載我們提供的所有用於維基百科問答的訓練後的模型和資料,請執行:

./download.sh

警告:這會下載一個 7.5GB 的 tar 壓縮包(解壓後 25GB),需要一些時間。

這會將資料儲存在各種模組的預設值指定的檔案路徑中的 data/ 中。通過將 DRQA_DATA 環境變數指定到其它地方,可以修改這個頂級目錄。

預設目錄結構(參見嵌入部分了解更多有關用於訓練的額外下載的資訊):

DrQA
├── data (or $DRQA_DATA)
    ├── datasets
    │   ├── SQuAD-v1.1-<train/dev>.<txt/json>
    │   ├── WebQuestions-<train/test>.txt
    │   ├── freebase-entities.txt
    │   ├── CuratedTrec-<train/test>.txt
    │   └── WikiMovies-<train/test/entities>.txt
    ├── reader
    │   ├── multitask.mdl
    │   └── single.mdl
    └── wikipedia
        ├── docs.db
        └── docs-tfidf-ngram=2-hash=16777216-tokenizer=simple.npz

不同模組的預設模型路徑也可以通過下面的程式碼進行修改,比如:

import drqa.reader
drqa.reader.set_default('model', '/path/to/model')
reader = drqa.reader.Predictor()  # Default model loaded for prediction

文件檢索器(Document Retriever)

使用維基百科(unigram 和 bigram、2^24 bin,簡單 tokenization)的 TF-IDF 模型在多個資料集(這是測試集,開發集是 SQuAD)上的評估結果:

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

連結:https://s3.amazonaws.com/fair-data/drqa/docs-tfidf-ngram%3D2-hash%3D16777216-tokenizer%3Dsimple.npz.gz

這裡 P@5 是指答案部分出現在前 5 個文件中的問題的百分比。

文件閱讀器(Document Reader)

僅在 SQuAD 上訓練的模型,在 SQuAD 背景中的評估結果:

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

連結:https://s3.amazonaws.com/fair-data/drqa/single.mdl

使用遠端監督(distant supervision)在沒有 NER/POS/lemma 功能的情況下訓練的模型,在完全維基百科環境中的多個資料集(這是測試集,開發集是 SQuAD)上的評估結果:

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

連結:https://s3.amazonaws.com/fair-data/drqa/multitask.mdl

維基百科

我們的完全規模實驗是在 2016 年 12 月 21 日轉存的英語版維基百科上執行的。這個轉存資料使用 WikiExtractor(https://github.com/attardi/wikiextractor)進行了處理,併為內部消岐、列表、索引和大綱頁面(通常僅包含連結的頁面)進行了過濾。我們將這些文件儲存成了一個 sqlite 資料庫,其中 drqa.retriever.DocDB 提供了一個介面。

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

連結:https://s3.amazonaws.com/fair-data/drqa/docs.db.gz

問答資料集

  • 用於 DrQA 訓練和評估的資料集可以在這裡找到:
  • SQuAD

訓練:https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json


開發:https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json


  • WebQuestions

訓練:http://nlp.stanford.edu/static/software/sempre/release-emnlp2013/lib/data/webquestions/dataset_11/webquestions.examples.train.json.bz2


測試:http://nlp.stanford.edu/static/software/sempre/release-emnlp2013/lib/data/webquestions/dataset_11/webquestions.examples.test.json.bz2


實體:https://s3.amazonaws.com/fair-data/drqa/freebase-entities.txt.gz


  • WikiMovies:訓練/測試/實體:https://s3.amazonaws.com/fair-data/drqa/WikiMovies.tar.gz(這是從 https://research.fb.com/downloads/babi/ 以預期格式重新託管的)
  • CuratedTrec:訓練/測試:https://s3.amazonaws.com/fair-data/drqa/CuratedTrec.tar.gz(這是從 https://github.com/brmson/dataset-factoid-curated 以預期格式重新託管的)

格式 A

retriever/eval.py、pipeline/eval.py 和 distant/generate.py 需要資料集是 .txt 檔案,且其中每一行都是 JSON 格式編碼的問答對,比如:

'{"question": "q1", "answer": ["a11", ..., "a1i"]}'
...
'{"question": "qN", "answer": ["aN1", ..., "aNi"]}'

將 SQuAD 和 WebQuestions 轉換成這種格式的指令碼包含在 scripts/convert,這是在 download.sh 中自動完成的。

格式 B

reader 目錄指令碼需要資料集是 .json 檔案,其中資料像 SQuAD 一樣排布:

file.json
├── "data"
│   └── [i]
│       ├── "paragraphs"
│       │   └── [j]
│       │       ├── "context": "paragraph text"
│       │       └── "qas"
│       │           └── [k]
│       │               ├── "answers"
│       │               │   └── [l]
│       │               │       ├── "answer_start": N
│       │               │       └── "text": "answer"
│       │               ├── "id": "<uuid>"
│       │               └── "question": "paragraph question?"
│       └── "title": "document id"
└── "version": 1.1

實體列表

一些資料集有(可能很大的)可選答案列表。比如,WikiMovies 的答案是 OMDb 實體,而 WebQuestions 則基於 Freebase。如果我們已經知道了候選項,我們可以通過丟棄不在這個列表中的任何更高得分範圍來強行使所有預測的答案必須在這個列表中。

DrQA 元件

文件檢索器

DrQA 並未繫結任何特定型別的檢索系統——只要其能有效地縮小搜尋空間並重點關注相關文件即可。

按照經典的問答系統的做法,我們納入了一個基於稀疏的、TF-IDF 加權的詞袋向量的有效文件檢索系統(非機器學習)。我們使用了 bags of hashed n-grams(這裡是 unigrams 和 bigrams)。

要了解如何在新文件上構建你自己的模型,參閱檢索器的 README:https://github.com/facebookresearch/DrQA/blob/master/scripts/retriever/README.md。

要互動式地查詢維基百科:

python scripts/retriever/interactive.py --model /path/to/model

如果 model 被忽略,就會使用我們的預設模型(假設已經下載了)。

為了評估該檢索器在一個資料集上的準確度(前 5 個的匹配率):

python scripts/retriever/eval.py /path/to/format/A/dataset.txt --model /path/to/model

文件閱讀器

DrQA 的文件閱讀器是一個多層迴圈神經網路機器理解模型,被訓練用來執行提取式的問答。也就是說,該模型會使用一個返回的文件中的一段文字來作為問題的答案。

該文件閱讀器的靈感來自於 SQuAD 資料集,並且也主要是在這個資料集上訓練的。它也可以在類似於 SQuAD 的任務上單獨使用,其中可以通過問題、包含在上下文中的答案來提供一個特定的語境。

要了解如何在 SQuAD 上訓練該文件閱讀器,參閱閱讀器的 README:https://github.com/facebookresearch/DrQA/blob/master/scripts/reader/README.md

要使用訓練後的模型互動式地詢問關於文字的問題:

python scripts/reader/interactive.py --model /path/to/model

同樣,這裡的 model 是可選的;如果忽略就會使用預設的模型。

要在資料集上執行模型預測:

python scripts/reader/predict.py /path/to/format/B/dataset.json --model /path/to/model

DrQA 流程

整個系統在 drqa.pipeline.DrQA 中連結到一起。

要使用完整的 DrQA 互動式地提問:

python scripts/pipeline/interactive.py

可選引數:

--reader-model Path to trained Document Reader model.
--retriever-model Path to Document Retriever model (tfidf).
--doc-db Path to Document DB.
--tokenizers String option specifying tokenizer type to use (e.g. 'corenlp').
--candidate-file List of candidates to restrict predictions to, one candidate per line.
--no-cuda Use CPU only.
--gpu Specify GPU device id to use.

要在資料集上執行預測:

python scripts/pipeline/predict.py /path/to/format/A/dataset.txt

可選引數:

--out-dir             Directory to write prediction file to (<dataset>-<model>-pipeline.preds).
--reader-model        Path to trained Document Reader model.
--retriever-model     Path to Document Retriever model (tfidf).
--doc-db              Path to Document DB.
--embedding-file      Expand dictionary to use all pretrained embeddings in this file (e.g. all glove vectors to minimize UNKs at test time).
--candidate-file      List of candidates to restrict predictions to, one candidate per line.
--n-docs              Number of docs to retrieve per query.
--top-n               Number of predictions to make per query.
--tokenizer           String option specifying tokenizer type to use (e.g. 'corenlp').
--no-cuda             Use CPU only.
--gpu                 Specify GPU device id to use.
--parallel            Use data parallel (split across GPU devices).
--num-workers         Number of CPU processes (for tokenizing, etc).
--batch-size          Document paragraph batching size (Reduce in case of GPU OOM).
--predict-batch-size  Question batching size (Reduce in case of CPU OOM).

遠端監督(DS:Distant Supervision)

當提供了來自額外資料集的遠端監督資料時,完全配置的 DrQA 的表現會顯著提升。給定問答對但不提供支援語境,我們可以使用字串匹配啟發式方法來自動將段落與這些訓練樣本關聯起來。

Question: What U.S. state’s motto is “Live free or Die”?

Answer: New Hampshire

DS Document: Live Free or Die “Live Free or Die” is the official motto of the U.S. state of New Hampshire, adopted by the state in 1945. It is possibly the best-known of all state mottos, partly because it conveys an assertive independence historically found in American political philosophy and partly because of its contrast to the milder sentiments found in other state mottos.

scripts/distant 目錄包含用於生成和檢查這種遠端監督資料的程式碼。

tokenizer

為了方便,我們提供了一些不同的 tokenizer 選項。在依賴包需求、執行開銷、速度和效能上,每一個選項都有自己的優勢和劣勢。對於我們報告的實驗,我們使用了 CoreNLP(但結果都是相似的)。

可用的 tokenizer:

  • CoreNLPTokenizer:使用 Stanford CoreNLP(選項:corenlp),我們使用了 v3.7.0,需要 Java 8
  • SpacyTokenizer:使用 spaCy(選項:spacy)
  • RegexpTokenizer:基於自定義正規表示式的 PTB 風格的 tokenizer(選項:regexp)
  • SimpleTokenizer:基本的字母-數字/非空的 tokenizer(選項:simple)

查閱字串選項名和 tokenizer 類別的對應列表:https://github.com/facebookresearch/DrQA/blob/master/drqa/tokenizers/__init__.py

引用

如果你在你的工作中使用 DrQA,請引用這篇 ACL 論文:

@inproceedings{chen2017reading,
  title={Reading {Wikipedia} to Answer Open-Domain Questions},
  author={Chen, Danqi and Fisch, Adam and Weston, Jason and Bordes, Antoine},
  booktitle={Association for Computational Linguistics (ACL)},
  year={2017}
}


與 ParlAI 連線

這個 DrQA 文件閱讀器實現與 ParlAI 中的文件閱讀器有緊密關聯。但是這裡的研究得到的擴充套件,以便能在開放域環境中與文件檢索器進行互動。即使當 ParlAI API 的限制解除時(比如在預處理和回答範圍等方面),它也或多或少在訓練上更高效,而且能實現稍微更好的表現。

我們也計劃將這個模型整合到 ParlAI 介面中,以便其閱讀器可以使用 ParlAI 進行可交替的訓練或在許多資料集上多工執行。有關 ParlAI 的更多資訊,可參閱機器之心文章《資源 | Facebook 開源人工智慧框架 ParlAI:可輕鬆訓練評估對話模型》。

證照

DrQA 使用 CC-BY-NC 證照。

論文:閱讀維基百科以回答開放域問題(Reading Wikipedia to Answer Open-Domain Questions)

資源 | Facebook開源DrQA的PyTorch實現:基於維基百科的問答系統

論文連結:https://arxiv.org/abs/1704.00051

本論文提出可使用維基百科作為唯一知識源來解決開放域問答問題(open-domain question answering):任何事實性問題的答案都是一篇維基百科文章裡面的一段文字。這種大規模機器閱讀任務將文件檢索難題(尋找相關文章)與文字的機器理解(在這些文章中確定答案的範圍)。我們的方法結合了基於二元語法雜湊(bigram hashing)和 TF-IDF 匹配的搜尋元件與一個訓練用於檢測維基百科段落中答案的多層迴圈神經網路。我們在多個已有問答資料集上的實驗表明:(1) 這兩個模組與當前的競爭者相比都有很高的競爭力,(2) 在它們的組合上使用遠端監督(distant supervision)的多工學習是在這種高難度任務上的有效完備系統。

相關文章