2019-05-06 11:56:56 +03:00
|
|
|
# coding: utf-8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2019-07-22 14:34:12 +03:00
|
|
|
import os
|
|
|
|
from os import path
|
2019-06-07 14:54:45 +03:00
|
|
|
import random
|
2019-06-19 10:15:43 +03:00
|
|
|
import datetime
|
|
|
|
from pathlib import Path
|
2019-06-07 14:54:45 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
from bin.wiki_entity_linking import wikipedia_processor as wp
|
|
|
|
from bin.wiki_entity_linking import training_set_creator, kb_creator
|
2019-06-18 14:20:40 +03:00
|
|
|
from bin.wiki_entity_linking.kb_creator import DESC_WIDTH
|
2019-05-06 11:56:56 +03:00
|
|
|
|
|
|
|
import spacy
|
|
|
|
from spacy.kb import KnowledgeBase
|
2019-06-19 10:15:43 +03:00
|
|
|
from spacy.util import minibatch, compounding
|
2019-05-06 11:56:56 +03:00
|
|
|
|
|
|
|
"""
|
|
|
|
Demonstrate how to build a knowledge base from WikiData and run an Entity Linking algorithm.
|
|
|
|
"""
|
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
ROOT_DIR = Path("C:/Users/Sofie/Documents/data/")
|
2019-07-18 11:22:24 +03:00
|
|
|
OUTPUT_DIR = ROOT_DIR / "wikipedia"
|
|
|
|
TRAINING_DIR = OUTPUT_DIR / "training_data_nel"
|
2019-05-06 11:56:56 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
PRIOR_PROB = OUTPUT_DIR / "prior_prob.csv"
|
|
|
|
ENTITY_COUNTS = OUTPUT_DIR / "entity_freq.csv"
|
|
|
|
ENTITY_DEFS = OUTPUT_DIR / "entity_defs.csv"
|
|
|
|
ENTITY_DESCR = OUTPUT_DIR / "entity_descriptions.csv"
|
2019-05-06 11:56:56 +03:00
|
|
|
|
2019-07-22 14:34:12 +03:00
|
|
|
KB_DIR = OUTPUT_DIR / "kb_1"
|
|
|
|
KB_FILE = "kb"
|
2019-07-18 11:22:24 +03:00
|
|
|
NLP_1_DIR = OUTPUT_DIR / "nlp_1"
|
|
|
|
NLP_2_DIR = OUTPUT_DIR / "nlp_2"
|
2019-05-06 11:56:56 +03:00
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# get latest-all.json.bz2 from https://dumps.wikimedia.org/wikidatawiki/entities/
|
2019-07-18 11:22:24 +03:00
|
|
|
WIKIDATA_JSON = ROOT_DIR / "wikidata" / "wikidata-20190304-all.json.bz2"
|
2019-06-19 10:15:43 +03:00
|
|
|
|
|
|
|
# get enwiki-latest-pages-articles-multistream.xml.bz2 from https://dumps.wikimedia.org/enwiki/latest/
|
2019-07-18 11:22:24 +03:00
|
|
|
ENWIKI_DUMP = (
|
|
|
|
ROOT_DIR / "wikipedia" / "enwiki-20190320-pages-articles-multistream.xml.bz2"
|
|
|
|
)
|
2019-06-19 10:15:43 +03:00
|
|
|
|
|
|
|
# KB construction parameters
|
2019-06-07 14:54:45 +03:00
|
|
|
MAX_CANDIDATES = 10
|
2019-06-16 22:14:45 +03:00
|
|
|
MIN_ENTITY_FREQ = 20
|
2019-06-07 14:54:45 +03:00
|
|
|
MIN_PAIR_OCC = 5
|
2019-06-18 14:20:40 +03:00
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# model training parameters
|
2019-06-14 16:55:26 +03:00
|
|
|
EPOCHS = 10
|
2019-06-29 15:52:36 +03:00
|
|
|
DROPOUT = 0.5
|
2019-06-18 14:20:40 +03:00
|
|
|
LEARN_RATE = 0.005
|
|
|
|
L2 = 1e-6
|
2019-06-28 17:22:58 +03:00
|
|
|
CONTEXT_WIDTH = 128
|
2019-05-06 11:56:56 +03:00
|
|
|
|
2019-06-11 12:40:58 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
def now():
|
|
|
|
return datetime.datetime.now()
|
|
|
|
|
|
|
|
|
2019-06-11 12:40:58 +03:00
|
|
|
def run_pipeline():
|
2019-06-19 10:15:43 +03:00
|
|
|
# set the appropriate booleans to define which parts of the pipeline should be re(run)
|
2019-07-18 11:22:24 +03:00
|
|
|
print("START", now())
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
2019-07-18 11:22:24 +03:00
|
|
|
nlp_1 = spacy.load("en_core_web_lg")
|
2019-06-13 17:25:39 +03:00
|
|
|
nlp_2 = None
|
|
|
|
kb_2 = None
|
2019-05-06 11:56:56 +03:00
|
|
|
|
|
|
|
# one-time methods to create KB and write to file
|
|
|
|
to_create_prior_probs = False
|
|
|
|
to_create_entity_counts = False
|
2019-06-16 22:14:45 +03:00
|
|
|
to_create_kb = False
|
2019-05-06 11:56:56 +03:00
|
|
|
|
|
|
|
# read KB back in from file
|
2019-06-26 16:55:26 +03:00
|
|
|
to_read_kb = True
|
2019-06-14 16:55:26 +03:00
|
|
|
to_test_kb = False
|
2019-06-05 01:09:46 +03:00
|
|
|
|
2019-05-06 16:13:50 +03:00
|
|
|
# create training dataset
|
2019-06-14 20:55:46 +03:00
|
|
|
create_wp_training = False
|
2019-05-06 11:56:56 +03:00
|
|
|
|
2019-06-11 12:40:58 +03:00
|
|
|
# train the EL pipe
|
2019-06-26 16:55:26 +03:00
|
|
|
train_pipe = True
|
|
|
|
measure_performance = True
|
2019-06-06 21:22:14 +03:00
|
|
|
|
2019-06-11 12:40:58 +03:00
|
|
|
# test the EL pipe on a simple example
|
2019-07-03 14:35:36 +03:00
|
|
|
to_test_pipeline = True
|
2019-06-06 20:51:27 +03:00
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
# write the NLP object, read back in and test again
|
2019-07-03 14:35:36 +03:00
|
|
|
to_write_nlp = True
|
|
|
|
to_read_nlp = True
|
2019-06-26 16:55:26 +03:00
|
|
|
test_from_file = False
|
2019-06-13 17:25:39 +03:00
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# STEP 1 : create prior probabilities from WP (run only once)
|
2019-05-06 11:56:56 +03:00
|
|
|
if to_create_prior_probs:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 1: to_create_prior_probs", now())
|
|
|
|
wp.read_prior_probs(ENWIKI_DUMP, PRIOR_PROB)
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# STEP 2 : deduce entity frequencies from WP (run only once)
|
2019-05-06 11:56:56 +03:00
|
|
|
if to_create_entity_counts:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 2: to_create_entity_counts", now())
|
|
|
|
wp.write_entity_counts(PRIOR_PROB, ENTITY_COUNTS, to_print=False)
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# STEP 3 : create KB and write to file (run only once)
|
2019-05-06 11:56:56 +03:00
|
|
|
if to_create_kb:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 3a: to_create_kb", now())
|
|
|
|
kb_1 = kb_creator.create_kb(
|
|
|
|
nlp=nlp_1,
|
|
|
|
max_entities_per_alias=MAX_CANDIDATES,
|
|
|
|
min_entity_freq=MIN_ENTITY_FREQ,
|
|
|
|
min_occ=MIN_PAIR_OCC,
|
|
|
|
entity_def_output=ENTITY_DEFS,
|
|
|
|
entity_descr_output=ENTITY_DESCR,
|
|
|
|
count_input=ENTITY_COUNTS,
|
|
|
|
prior_prob_input=PRIOR_PROB,
|
|
|
|
wikidata_input=WIKIDATA_JSON,
|
|
|
|
)
|
2019-06-13 17:25:39 +03:00
|
|
|
print("kb entities:", kb_1.get_size_entities())
|
|
|
|
print("kb aliases:", kb_1.get_size_aliases())
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 3b: write KB and NLP", now())
|
2019-07-22 14:34:12 +03:00
|
|
|
|
|
|
|
if not path.exists(KB_DIR):
|
|
|
|
os.makedirs(KB_DIR)
|
|
|
|
kb_1.dump(KB_DIR / KB_FILE)
|
2019-06-13 17:25:39 +03:00
|
|
|
nlp_1.to_disk(NLP_1_DIR)
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
|
|
|
# STEP 4 : read KB back in from file
|
|
|
|
if to_read_kb:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 4: to_read_kb", now())
|
2019-06-13 17:25:39 +03:00
|
|
|
nlp_2 = spacy.load(NLP_1_DIR)
|
|
|
|
kb_2 = KnowledgeBase(vocab=nlp_2.vocab, entity_vector_length=DESC_WIDTH)
|
2019-07-22 14:34:12 +03:00
|
|
|
kb_2.load_bulk(KB_DIR / KB_FILE)
|
2019-06-13 17:25:39 +03:00
|
|
|
print("kb entities:", kb_2.get_size_entities())
|
|
|
|
print("kb aliases:", kb_2.get_size_aliases())
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
|
|
|
# test KB
|
|
|
|
if to_test_kb:
|
2019-06-18 14:20:40 +03:00
|
|
|
check_kb(kb_2)
|
2019-05-06 11:56:56 +03:00
|
|
|
print()
|
|
|
|
|
|
|
|
# STEP 5: create a training dataset from WP
|
|
|
|
if create_wp_training:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 5: create training dataset", now())
|
|
|
|
training_set_creator.create_training(
|
|
|
|
wikipedia_input=ENWIKI_DUMP,
|
|
|
|
entity_def_input=ENTITY_DEFS,
|
|
|
|
training_output=TRAINING_DIR,
|
|
|
|
)
|
2019-05-07 17:03:42 +03:00
|
|
|
|
2019-06-18 14:20:40 +03:00
|
|
|
# STEP 6: create and train the entity linking pipe
|
2019-06-25 17:09:22 +03:00
|
|
|
if train_pipe:
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 6: training Entity Linking pipe", now())
|
2019-06-29 15:52:36 +03:00
|
|
|
type_to_int = {label: i for i, label in enumerate(nlp_2.entity.labels)}
|
|
|
|
print(" -analysing", len(type_to_int), "different entity types")
|
2019-07-18 11:22:24 +03:00
|
|
|
el_pipe = nlp_2.create_pipe(
|
|
|
|
name="entity_linker",
|
|
|
|
config={
|
|
|
|
"context_width": CONTEXT_WIDTH,
|
|
|
|
"pretrained_vectors": nlp_2.vocab.vectors.name,
|
|
|
|
"type_to_int": type_to_int,
|
|
|
|
},
|
|
|
|
)
|
2019-06-25 17:09:22 +03:00
|
|
|
el_pipe.set_kb(kb_2)
|
|
|
|
nlp_2.add_pipe(el_pipe, last=True)
|
2019-06-14 20:55:46 +03:00
|
|
|
|
2019-06-25 17:09:22 +03:00
|
|
|
other_pipes = [pipe for pipe in nlp_2.pipe_names if pipe != "entity_linker"]
|
|
|
|
with nlp_2.disable_pipes(*other_pipes): # only train Entity Linking
|
|
|
|
optimizer = nlp_2.begin_training()
|
|
|
|
optimizer.learn_rate = LEARN_RATE
|
|
|
|
optimizer.L2 = L2
|
2019-06-14 20:55:46 +03:00
|
|
|
|
2019-06-19 10:15:43 +03:00
|
|
|
# define the size (nr of entities) of training and dev set
|
2019-07-03 18:48:09 +03:00
|
|
|
train_limit = 5000
|
|
|
|
dev_limit = 5000
|
2019-06-10 22:25:26 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
# for training, get pos & neg instances that correspond to entries in the kb
|
|
|
|
train_data = training_set_creator.read_training(
|
|
|
|
nlp=nlp_2,
|
|
|
|
training_dir=TRAINING_DIR,
|
|
|
|
dev=False,
|
|
|
|
limit=train_limit,
|
|
|
|
kb=el_pipe.kb,
|
|
|
|
)
|
2019-06-16 22:14:45 +03:00
|
|
|
|
|
|
|
print("Training on", len(train_data), "articles")
|
|
|
|
print()
|
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
# for testing, get all pos instances, whether or not they are in the kb
|
|
|
|
dev_data = training_set_creator.read_training(
|
|
|
|
nlp=nlp_2, training_dir=TRAINING_DIR, dev=True, limit=dev_limit, kb=None
|
|
|
|
)
|
2019-06-18 14:20:40 +03:00
|
|
|
|
|
|
|
print("Dev testing on", len(dev_data), "articles")
|
|
|
|
print()
|
|
|
|
|
2019-06-16 22:14:45 +03:00
|
|
|
if not train_data:
|
|
|
|
print("Did not find any training data")
|
|
|
|
else:
|
|
|
|
for itn in range(EPOCHS):
|
|
|
|
random.shuffle(train_data)
|
|
|
|
losses = {}
|
|
|
|
batches = minibatch(train_data, size=compounding(4.0, 128.0, 1.001))
|
|
|
|
batchnr = 0
|
|
|
|
|
|
|
|
with nlp_2.disable_pipes(*other_pipes):
|
|
|
|
for batch in batches:
|
|
|
|
try:
|
|
|
|
docs, golds = zip(*batch)
|
|
|
|
nlp_2.update(
|
2019-07-18 11:22:24 +03:00
|
|
|
docs=docs,
|
|
|
|
golds=golds,
|
2019-06-18 14:20:40 +03:00
|
|
|
sgd=optimizer,
|
2019-06-16 22:14:45 +03:00
|
|
|
drop=DROPOUT,
|
|
|
|
losses=losses,
|
|
|
|
)
|
|
|
|
batchnr += 1
|
|
|
|
except Exception as e:
|
2019-06-17 15:39:40 +03:00
|
|
|
print("Error updating batch:", e)
|
2019-06-16 22:14:45 +03:00
|
|
|
|
2019-06-17 15:39:40 +03:00
|
|
|
if batchnr > 0:
|
2019-07-03 18:48:09 +03:00
|
|
|
el_pipe.cfg["context_weight"] = 1
|
|
|
|
el_pipe.cfg["prior_weight"] = 1
|
2019-07-18 11:22:24 +03:00
|
|
|
dev_acc_context, _ = _measure_acc(dev_data, el_pipe)
|
|
|
|
losses["entity_linker"] = losses["entity_linker"] / batchnr
|
|
|
|
print(
|
|
|
|
"Epoch, train loss",
|
|
|
|
itn,
|
|
|
|
round(losses["entity_linker"], 2),
|
|
|
|
" / dev acc avg",
|
|
|
|
round(dev_acc_context, 3),
|
|
|
|
)
|
2019-06-18 14:20:40 +03:00
|
|
|
|
|
|
|
# STEP 7: measure the performance of our trained pipe on an independent dev set
|
2019-06-16 22:14:45 +03:00
|
|
|
if len(dev_data) and measure_performance:
|
2019-06-13 17:25:39 +03:00
|
|
|
print()
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 7: performance measurement of Entity Linking pipe", now())
|
2019-06-13 17:25:39 +03:00
|
|
|
print()
|
2019-06-12 14:37:05 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
counts, acc_r, acc_r_d, acc_p, acc_p_d, acc_o, acc_o_d = _measure_baselines(
|
|
|
|
dev_data, kb_2
|
|
|
|
)
|
2019-06-19 10:15:43 +03:00
|
|
|
print("dev counts:", sorted(counts.items(), key=lambda x: x[0]))
|
2019-07-18 11:22:24 +03:00
|
|
|
|
|
|
|
oracle_by_label = [(x, round(y, 3)) for x, y in acc_o_d.items()]
|
|
|
|
print("dev acc oracle:", round(acc_o, 3), oracle_by_label)
|
|
|
|
|
|
|
|
random_by_label = [(x, round(y, 3)) for x, y in acc_r_d.items()]
|
|
|
|
print("dev acc random:", round(acc_r, 3), random_by_label)
|
|
|
|
|
|
|
|
prior_by_label = [(x, round(y, 3)) for x, y in acc_p_d.items()]
|
|
|
|
print("dev acc prior:", round(acc_p, 3), prior_by_label)
|
2019-06-18 14:20:40 +03:00
|
|
|
|
2019-07-03 18:48:09 +03:00
|
|
|
# using only context
|
|
|
|
el_pipe.cfg["context_weight"] = 1
|
|
|
|
el_pipe.cfg["prior_weight"] = 0
|
2019-07-18 11:22:24 +03:00
|
|
|
dev_acc_context, dev_acc_cont_d = _measure_acc(dev_data, el_pipe)
|
|
|
|
context_by_label = [(x, round(y, 3)) for x, y in dev_acc_cont_d.items()]
|
|
|
|
print("dev acc context avg:", round(dev_acc_context, 3), context_by_label)
|
2019-07-03 18:48:09 +03:00
|
|
|
|
|
|
|
# measuring combined accuracy (prior + context)
|
|
|
|
el_pipe.cfg["context_weight"] = 1
|
|
|
|
el_pipe.cfg["prior_weight"] = 1
|
2019-07-18 11:22:24 +03:00
|
|
|
dev_acc_combo, dev_acc_combo_d = _measure_acc(dev_data, el_pipe)
|
|
|
|
combo_by_label = [(x, round(y, 3)) for x, y in dev_acc_combo_d.items()]
|
|
|
|
print("dev acc combo avg:", round(dev_acc_combo, 3), combo_by_label)
|
2019-06-14 16:55:26 +03:00
|
|
|
|
2019-06-25 17:09:22 +03:00
|
|
|
# STEP 8: apply the EL pipe on a toy example
|
|
|
|
if to_test_pipeline:
|
|
|
|
print()
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 8: applying Entity Linking to toy example", now())
|
2019-06-25 17:09:22 +03:00
|
|
|
print()
|
|
|
|
run_el_toy_example(nlp=nlp_2)
|
2019-06-13 17:25:39 +03:00
|
|
|
|
2019-06-25 17:09:22 +03:00
|
|
|
# STEP 9: write the NLP pipeline (including entity linker) to file
|
|
|
|
if to_write_nlp:
|
|
|
|
print()
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STEP 9: testing NLP IO", now())
|
2019-06-25 17:09:22 +03:00
|
|
|
print()
|
|
|
|
print("writing to", NLP_2_DIR)
|
2019-07-03 18:48:09 +03:00
|
|
|
nlp_2.to_disk(NLP_2_DIR)
|
2019-06-25 17:09:22 +03:00
|
|
|
print()
|
|
|
|
|
|
|
|
# verify that the IO has gone correctly
|
|
|
|
if to_read_nlp:
|
2019-06-13 17:25:39 +03:00
|
|
|
print("reading from", NLP_2_DIR)
|
|
|
|
nlp_3 = spacy.load(NLP_2_DIR)
|
|
|
|
|
2019-06-26 14:53:10 +03:00
|
|
|
print("running toy example with NLP 3")
|
|
|
|
run_el_toy_example(nlp=nlp_3)
|
2019-06-25 17:09:22 +03:00
|
|
|
|
2019-06-26 14:53:10 +03:00
|
|
|
# testing performance with an NLP model from file
|
|
|
|
if test_from_file:
|
|
|
|
nlp_2 = spacy.load(NLP_1_DIR)
|
|
|
|
nlp_3 = spacy.load(NLP_2_DIR)
|
|
|
|
el_pipe = nlp_3.get_pipe("entity_linker")
|
2019-06-25 17:09:22 +03:00
|
|
|
|
2019-06-29 15:52:36 +03:00
|
|
|
dev_limit = 5000
|
2019-07-18 11:22:24 +03:00
|
|
|
dev_data = training_set_creator.read_training(
|
2019-07-18 14:35:10 +03:00
|
|
|
nlp=nlp_2, training_dir=TRAINING_DIR, dev=True, limit=dev_limit, kb=None
|
2019-07-18 11:22:24 +03:00
|
|
|
)
|
2019-06-26 14:53:10 +03:00
|
|
|
|
|
|
|
print("Dev testing from file on", len(dev_data), "articles")
|
|
|
|
print()
|
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
dev_acc_combo, dev_acc_combo_dict = _measure_acc(dev_data, el_pipe)
|
|
|
|
combo_by_label = [(x, round(y, 3)) for x, y in dev_acc_combo_dict.items()]
|
|
|
|
print("dev acc combo avg:", round(dev_acc_combo, 3), combo_by_label)
|
2019-05-06 11:56:56 +03:00
|
|
|
|
|
|
|
print()
|
2019-07-18 11:22:24 +03:00
|
|
|
print("STOP", now())
|
2019-06-11 12:40:58 +03:00
|
|
|
|
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
def _measure_acc(data, el_pipe=None, error_analysis=False):
|
2019-06-25 17:09:22 +03:00
|
|
|
# If the docs in the data require further processing with an entity linker, set el_pipe
|
2019-06-14 20:55:46 +03:00
|
|
|
correct_by_label = dict()
|
|
|
|
incorrect_by_label = dict()
|
2019-06-11 12:40:58 +03:00
|
|
|
|
2019-06-12 23:05:53 +03:00
|
|
|
docs = [d for d, g in data if len(d) > 0]
|
2019-06-25 17:09:22 +03:00
|
|
|
if el_pipe is not None:
|
2019-06-26 16:55:26 +03:00
|
|
|
docs = list(el_pipe.pipe(docs))
|
2019-06-12 23:05:53 +03:00
|
|
|
golds = [g for d, g in data if len(d) > 0]
|
2019-06-11 12:40:58 +03:00
|
|
|
|
|
|
|
for doc, gold in zip(docs, golds):
|
2019-06-12 14:37:05 +03:00
|
|
|
try:
|
|
|
|
correct_entries_per_article = dict()
|
2019-07-19 13:36:15 +03:00
|
|
|
for entity, kb_dict in gold.links.items():
|
|
|
|
start, end = entity
|
2019-07-18 11:22:24 +03:00
|
|
|
# only evaluating on positive examples
|
2019-07-19 13:36:15 +03:00
|
|
|
for gold_kb, value in kb_dict.items():
|
|
|
|
if value:
|
2019-07-22 14:34:12 +03:00
|
|
|
offset = str(start) + "-" + str(end)
|
|
|
|
correct_entries_per_article[offset] = gold_kb
|
2019-06-12 14:37:05 +03:00
|
|
|
|
|
|
|
for ent in doc.ents:
|
2019-06-14 20:55:46 +03:00
|
|
|
ent_label = ent.label_
|
|
|
|
pred_entity = ent.kb_id_
|
|
|
|
start = ent.start_char
|
|
|
|
end = ent.end_char
|
2019-07-18 11:22:24 +03:00
|
|
|
offset = str(start) + "-" + str(end)
|
|
|
|
gold_entity = correct_entries_per_article.get(offset, None)
|
2019-06-14 20:55:46 +03:00
|
|
|
# the gold annotations are not complete so we can't evaluate missing annotations as 'wrong'
|
|
|
|
if gold_entity is not None:
|
|
|
|
if gold_entity == pred_entity:
|
|
|
|
correct = correct_by_label.get(ent_label, 0)
|
|
|
|
correct_by_label[ent_label] = correct + 1
|
|
|
|
else:
|
|
|
|
incorrect = incorrect_by_label.get(ent_label, 0)
|
|
|
|
incorrect_by_label[ent_label] = incorrect + 1
|
2019-06-29 15:52:36 +03:00
|
|
|
if error_analysis:
|
|
|
|
print(ent.text, "in", doc)
|
2019-07-18 11:22:24 +03:00
|
|
|
print(
|
|
|
|
"Predicted",
|
|
|
|
pred_entity,
|
|
|
|
"should have been",
|
|
|
|
gold_entity,
|
|
|
|
)
|
2019-06-29 15:52:36 +03:00
|
|
|
print()
|
2019-06-12 14:37:05 +03:00
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
print("Error assessing accuracy", e)
|
2019-06-11 12:40:58 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
acc, acc_by_label = calculate_acc(correct_by_label, incorrect_by_label)
|
2019-06-17 15:39:40 +03:00
|
|
|
return acc, acc_by_label
|
|
|
|
|
|
|
|
|
|
|
|
def _measure_baselines(data, kb):
|
2019-06-18 14:20:40 +03:00
|
|
|
# Measure 3 performance baselines: random selection, prior probabilities, and 'oracle' prediction for upper bound
|
2019-07-18 11:22:24 +03:00
|
|
|
counts_d = dict()
|
2019-06-18 19:38:09 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
random_correct_d = dict()
|
|
|
|
random_incorrect_d = dict()
|
2019-06-17 15:39:40 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
oracle_correct_d = dict()
|
|
|
|
oracle_incorrect_d = dict()
|
2019-06-17 15:39:40 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
prior_correct_d = dict()
|
|
|
|
prior_incorrect_d = dict()
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
docs = [d for d, g in data if len(d) > 0]
|
|
|
|
golds = [g for d, g in data if len(d) > 0]
|
|
|
|
|
|
|
|
for doc, gold in zip(docs, golds):
|
|
|
|
try:
|
|
|
|
correct_entries_per_article = dict()
|
2019-07-19 13:36:15 +03:00
|
|
|
for entity, kb_dict in gold.links.items():
|
|
|
|
start, end = entity
|
|
|
|
for gold_kb, value in kb_dict.items():
|
|
|
|
# only evaluating on positive examples
|
|
|
|
if value:
|
2019-07-22 14:34:12 +03:00
|
|
|
offset = str(start) + "-" + str(end)
|
|
|
|
correct_entries_per_article[offset] = gold_kb
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
for ent in doc.ents:
|
2019-07-18 11:22:24 +03:00
|
|
|
label = ent.label_
|
2019-06-17 15:39:40 +03:00
|
|
|
start = ent.start_char
|
|
|
|
end = ent.end_char
|
2019-07-18 11:22:24 +03:00
|
|
|
offset = str(start) + "-" + str(end)
|
|
|
|
gold_entity = correct_entries_per_article.get(offset, None)
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
# the gold annotations are not complete so we can't evaluate missing annotations as 'wrong'
|
|
|
|
if gold_entity is not None:
|
2019-07-18 11:22:24 +03:00
|
|
|
counts_d[label] = counts_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
candidates = kb.get_candidates(ent.text)
|
|
|
|
oracle_candidate = ""
|
|
|
|
best_candidate = ""
|
|
|
|
random_candidate = ""
|
|
|
|
if candidates:
|
2019-06-24 11:55:04 +03:00
|
|
|
scores = []
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
for c in candidates:
|
|
|
|
scores.append(c.prior_prob)
|
|
|
|
if c.entity_ == gold_entity:
|
|
|
|
oracle_candidate = c.entity_
|
|
|
|
|
|
|
|
best_index = scores.index(max(scores))
|
|
|
|
best_candidate = candidates[best_index].entity_
|
|
|
|
random_candidate = random.choice(candidates).entity_
|
|
|
|
|
|
|
|
if gold_entity == best_candidate:
|
2019-07-18 11:22:24 +03:00
|
|
|
prior_correct_d[label] = prior_correct_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
else:
|
2019-07-18 11:22:24 +03:00
|
|
|
prior_incorrect_d[label] = prior_incorrect_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
if gold_entity == random_candidate:
|
2019-07-18 11:22:24 +03:00
|
|
|
random_correct_d[label] = random_correct_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
else:
|
2019-07-18 11:22:24 +03:00
|
|
|
random_incorrect_d[label] = random_incorrect_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
if gold_entity == oracle_candidate:
|
2019-07-18 11:22:24 +03:00
|
|
|
oracle_correct_d[label] = oracle_correct_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
else:
|
2019-07-18 11:22:24 +03:00
|
|
|
oracle_incorrect_d[label] = oracle_incorrect_d.get(label, 0) + 1
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
print("Error assessing accuracy", e)
|
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
acc_prior, acc_prior_d = calculate_acc(prior_correct_d, prior_incorrect_d)
|
|
|
|
acc_rand, acc_rand_d = calculate_acc(random_correct_d, random_incorrect_d)
|
|
|
|
acc_oracle, acc_oracle_d = calculate_acc(oracle_correct_d, oracle_incorrect_d)
|
2019-06-17 15:39:40 +03:00
|
|
|
|
2019-07-18 11:22:24 +03:00
|
|
|
return (
|
|
|
|
counts_d,
|
|
|
|
acc_rand,
|
|
|
|
acc_rand_d,
|
|
|
|
acc_prior,
|
|
|
|
acc_prior_d,
|
|
|
|
acc_oracle,
|
|
|
|
acc_oracle_d,
|
|
|
|
)
|
2019-06-17 15:39:40 +03:00
|
|
|
|
|
|
|
|
|
|
|
def calculate_acc(correct_by_label, incorrect_by_label):
|
2019-06-14 20:55:46 +03:00
|
|
|
acc_by_label = dict()
|
|
|
|
total_correct = 0
|
|
|
|
total_incorrect = 0
|
2019-06-18 01:05:47 +03:00
|
|
|
all_keys = set()
|
|
|
|
all_keys.update(correct_by_label.keys())
|
|
|
|
all_keys.update(incorrect_by_label.keys())
|
|
|
|
for label in sorted(all_keys):
|
|
|
|
correct = correct_by_label.get(label, 0)
|
2019-06-14 20:55:46 +03:00
|
|
|
incorrect = incorrect_by_label.get(label, 0)
|
|
|
|
total_correct += correct
|
|
|
|
total_incorrect += incorrect
|
|
|
|
if correct == incorrect == 0:
|
|
|
|
acc_by_label[label] = 0
|
|
|
|
else:
|
|
|
|
acc_by_label[label] = correct / (correct + incorrect)
|
|
|
|
acc = 0
|
|
|
|
if not (total_correct == total_incorrect == 0):
|
|
|
|
acc = total_correct / (total_correct + total_incorrect)
|
|
|
|
return acc, acc_by_label
|
|
|
|
|
|
|
|
|
2019-06-18 14:20:40 +03:00
|
|
|
def check_kb(kb):
|
2019-06-14 20:55:46 +03:00
|
|
|
for mention in ("Bush", "Douglas Adams", "Homer", "Brazil", "China"):
|
|
|
|
candidates = kb.get_candidates(mention)
|
|
|
|
|
|
|
|
print("generating candidates for " + mention + " :")
|
|
|
|
for c in candidates:
|
2019-07-18 11:22:24 +03:00
|
|
|
print(
|
|
|
|
" ",
|
|
|
|
c.prior_prob,
|
|
|
|
c.alias_,
|
|
|
|
"-->",
|
|
|
|
c.entity_ + " (freq=" + str(c.entity_freq) + ")",
|
|
|
|
)
|
2019-06-14 20:55:46 +03:00
|
|
|
print()
|
2019-06-11 12:40:58 +03:00
|
|
|
|
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
def run_el_toy_example(nlp):
|
2019-07-18 11:22:24 +03:00
|
|
|
text = (
|
|
|
|
"In The Hitchhiker's Guide to the Galaxy, written by Douglas Adams, "
|
|
|
|
"Douglas reminds us to always bring our towel, even in China or Brazil. "
|
|
|
|
"The main character in Doug's novel is the man Arthur Dent, "
|
2019-07-19 13:36:15 +03:00
|
|
|
"but Dougledydoug doesn't write about George Washington or Homer Simpson."
|
2019-07-18 11:22:24 +03:00
|
|
|
)
|
2019-06-11 12:40:58 +03:00
|
|
|
doc = nlp(text)
|
2019-06-17 15:39:40 +03:00
|
|
|
print(text)
|
2019-06-11 12:40:58 +03:00
|
|
|
for ent in doc.ents:
|
2019-06-19 10:15:43 +03:00
|
|
|
print(" ent", ent.text, ent.label_, ent.kb_id_)
|
2019-06-11 12:40:58 +03:00
|
|
|
print()
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2019-06-13 17:25:39 +03:00
|
|
|
run_pipeline()
|