BERT - изменить файл прогнозов run_squad.py - PullRequest
0 голосов
/ 20 июня 2019

Я новичок в BERT и Я пытаюсь отредактировать вывод run_squad.py для построения системы ответов на вопросы и получения выходного файла со следующей структурой :

{
    "data": [
      {
            "id": "ID1",
            "title": "Alan_Turing",
            "question": "When Alan Turing was born?",
            "context": "Alan Mathison Turing (23 June 1912 – 7 June 1954) was an English mathematician, computer scientist, logician, cryptanalyst, philosopher and theoretical biologist. [...] . However, both Julius and Ethel wanted their children to be brought up in Britain, so they moved to Maida Vale, London, where Alan Turing was born on 23 June 1912, as recorded by a blue plaque on the outside of the house of his birth, later the Colonnade Hotel. Turing had an elder brother, John (the father of Sir John Dermot Turing, 12th Baronet of the Turing baronets).",
            "answers": [
              {"text": "on 23 June 1912",   "probability": 0.891726, "start_logit": 4.075,  "end_logit": 4.15},
              {"text": "on 23 June", "probability": 0.091726, "start_logit": 2.075, "end_logit": 1.15},
              {"text": "June 1912", "probability": 0.051726, "start_logit": 1.075, "end_logit": 0.854}
            ]
        },
        {
            "id": "ID2",
            "title": "Title2",
            "question": "Question2",
            "context": "Context 2 ...",
            "answers": [
              {"text": "text1", "probability": 0.891726, "start_logit": 4.075, "end_logit": 4.15},
              {"text": "text2", "probability": 0.091726, "start_logit": 2.075, "end_logit": 1.15},
              {"text": "text3", "probability": 0.051726, "start_logit": 1.075, "end_logit": 0.854}
            ]
        }
    ]
}

Прежде всего, в функции read_squad_example (строка 227 из run_squad.py ) BERT считывает JSON-файл SQuAD (входной файл) в список SquadExampleэтот файл содержит первые четыре поля, которые мне нужны: id, заголовок, вопрос и контекст.

После этого SquadExamples преобразуются в объекты, после чего может начинаться фаза write_predictions (строка 741).

В write_predictions BERT записать выходной файл с именем nbest_predictions.json, содержащий все возможные ответы для определенного контекста с вероятностью, связанной с ним.

В строках 891-898 Iдумаю, что последние четыре поля, которые мне нужны (текст, вероятность, start_logit, end_logit) добавлены:

nbest_json = []
    for (i, entry) in enumerate(nbest):
      output = collections.OrderedDict()
      output["text"] = entry.text
      output["probability"] = probs[i]
      output["start_logit"] = entry.start_logit
      output["end_logit"] = entry.end_logit
nbest_json.append(output)

Выходной файл nbest_predictions.json имеет следующую структуру:

{
    "ID-1": [
        {
            "text": "text1", 
            "probability": 0.3617, 
            "start_logit": 4.0757, 
            "end_logit": 4.1554
        }, {
            "text": "text2", 
            "probability": 0.0036, 
            "start_logit": -0.5180, 
            "end_logit": 4.1554
        }
    ], 
    "ID-2": [
        {
            "text": "text1", 
            "probability": 0.2487, 
            "start_logit": -1.6009, 
            "end_logit": -0.2818
        }, {
            "text": "text2", 
            "probability": 0.0070, 
            "start_logit": -0.9566, 
            "end_logit": -1.5770
        }
    ]
}

Сейчас... Я не совсем понимаю, как лучше всегоФайл _predictions создан.Как я могу отредактировать эту функцию и получить файл json, структурированный, как я указал в начале моего поста?

Размышляя над этим, я думаю, что у меня есть две возможности:

  1. Создайте новую структуру данных и добавьте нужные мне поля.
  2. Отредактируйте функцию write_predictions, чтобы структурировать nbest_predictions.json так, как я хочу.

Какое лучшее решение?

В настоящее время я написал новую функцию, которая читает входной файл и добавляет к структуре данных мой идентификатор, заголовок, вопрос и контекст:

def read_squad_examples2(input_file, is_training):
  # SQUAD json file to list of SquadExamples #
  with tf.gfile.Open(input_file, "r") as reader:
    input_data = json.load(reader)["data"]

  def is_whitespace(c):
    if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
      return True
    return False

  data = {}
  sup_data = [] 

  for entry in input_data:
    entry_title = entry["title"]
    data["title"] = entry_title;
    for paragraph in entry["paragraphs"]:
      paragraph_text = paragraph["context"]
      data["context"] = paragraph_text;
      for qa in paragraph["qas"]:
        qas_id = qa["id"]
        data["id"] = qas_id;
        question_text = qa["question"]
        data["question"] = question_text

        sup_data.append(data)

  my_json = json.dumps(sup_data)

  return my_json

Что я получаю:

[{
    "question": "Question 1?",
    "id": "ID 1 ",
    "context": "The context 1",
    "title": "Title 1"
}, {
    "question": "Question 2?",
    "id": "ID 2 ",
    "context": "The context 2",
    "title": "Title 2"
}]

И на этом этапе, как я могу добавить к этой структуре данных поле answers, содержащее "текст", "вероятность", "start_logit" и "end_logit"?

Заранее спасибо.

...