|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Created on Mon Sep 3 17:14:47 2018 |
| 5 | +
|
| 6 | +@author: Emmanouil Theofanis Chourdakis <e.t.chourdakis@qmul.ac.uk> |
| 7 | +
|
| 8 | +Functions that do spatial role labeling. Relation extraction is done |
| 9 | +using sklearn with features extracted from the sentence based on the following paper: |
| 10 | +cd |
| 11 | +Nichols, Eric, and Fadi Botros. |
| 12 | +"SpRL-CWW: Spatial relation classification with independent multi-class models." |
| 13 | +Proceedings of the 9th International Workshop on Semantic Evaluation (SemEval 2015) |
| 14 | +""" |
| 15 | + |
| 16 | +from sklearn.externals import joblib |
| 17 | +import spacy |
| 18 | + |
| 19 | + |
| 20 | +def get_dep_path(span1, span2): |
| 21 | + assert span1.sent == span2.sent, "sent1: {}, span1: {}, sent2: {}, span2: {}".format(span1.sent, span1, span2.sent, span2) |
| 22 | + |
| 23 | + up = [] |
| 24 | + down = [] |
| 25 | + |
| 26 | + head = span1[0] |
| 27 | + while head.dep_ != 'ROOT': |
| 28 | + up.append(head) |
| 29 | + head = head.head |
| 30 | + up.append(head) |
| 31 | + |
| 32 | + head = span2[0] |
| 33 | + while head.dep_ != 'ROOT': |
| 34 | + down.append(head) |
| 35 | + head = head.head |
| 36 | + down.append(head) |
| 37 | + down.reverse() |
| 38 | + |
| 39 | + for n1, t1 in enumerate(up): |
| 40 | + for n2, t2 in enumerate(down): |
| 41 | + if t1 == t2: |
| 42 | + return ["{}::{}".format(u.dep_, 'up') for u in up[1:n1]] + ["{}::{}".format(d.dep_, 'down') for d in down[n2:]] |
| 43 | + |
| 44 | +def extract_relation_features(relation): |
| 45 | + F = {} # Feature dict |
| 46 | + |
| 47 | + trigger = relation[1] |
| 48 | + args = [relation[0], relation[2]] |
| 49 | + |
| 50 | + # Extract features relating to trigger |
| 51 | + #trigger_head = get_head(trigger) |
| 52 | + |
| 53 | + for n, token in enumerate(trigger): |
| 54 | + F['TF1T{}'.format(n)] = token.text |
| 55 | + F['TF2T{}'.format(n)] = token.lemma_ |
| 56 | + F['TF3T{}'.format(n)] = token.pos_ |
| 57 | + F['TF4T{}'.format(n)] = "::".join([token.lemma_, token.pos_]) # RF.2 concat RF.1 |
| 58 | + |
| 59 | + # Extract features relating to the two arguments |
| 60 | + for a, arg in enumerate(args): |
| 61 | + if arg is not None: |
| 62 | + for n, token in enumerate(arg): |
| 63 | + F['A{}F5T{}'.format(a, n)] = token.text |
| 64 | + F['A{}F6T{}'.format(a, n)] = token.lemma_ |
| 65 | + F['A{}F7T{}'.format(a, n)] = token.pos_ |
| 66 | + F['A{}F8T{}'.format(a, n)] = "::".join([token.lemma_, token.pos_]) |
| 67 | + |
| 68 | + |
| 69 | + if arg[-1].i < trigger[0].i: |
| 70 | + F['A{}F12'.format(a)] = 'LEFT' |
| 71 | + F['A{}F22'.format(a)] = trigger[0].i - arg[-1].i |
| 72 | + elif arg[0].i > trigger[-1].i: |
| 73 | + F['A{}F12'.format(a)] = 'RIGHT' |
| 74 | + F['A{}F22'.format(a)] = arg[0].i - trigger[-1].i |
| 75 | + |
| 76 | + |
| 77 | + path = get_dep_path(arg, trigger) |
| 78 | + for np, p in enumerate(path): |
| 79 | + F['A{}F17E{}'.format(a, np)] = p |
| 80 | + F['A{}F20'.format(a)] = len(path) |
| 81 | + F['A{}F24'.format(a)] = False |
| 82 | + else: |
| 83 | + F['A{}F24'.format(a)] = True |
| 84 | + |
| 85 | + # Joint features |
| 86 | + if 'A0F12' in F and 'A1F12' in F: |
| 87 | + F['F13'] = "::".join([F['A0F12'],F['A1F12']]) |
| 88 | + if F['A0F12'] == F['A1F12']: |
| 89 | + F['14'] = True |
| 90 | + else: |
| 91 | + F['14'] = False |
| 92 | + |
| 93 | + if 'F13' in F: |
| 94 | + for n, token in enumerate(trigger): |
| 95 | + F['14T{}'.format(n)] = '::'.join([F['F13'], token.lemma_]) |
| 96 | + |
| 97 | + if 'A0F22' in F and 'A1F22' in F: |
| 98 | + F['F23'] = F['A0F22'] + F['A1F22'] |
| 99 | + |
| 100 | + return F |
| 101 | + |
| 102 | +def extract_candidate_relations_from_sents(sents, gold_relations): |
| 103 | + candidate_relations = [] |
| 104 | + candidate_labels = [] |
| 105 | + |
| 106 | + for sent in sents: |
| 107 | + |
| 108 | + triggers = [t for t in sent.ents if t.label_ == 'SPATIAL_INDICATOR'] |
| 109 | + trajectors = [t for t in sent.ents if t.label_ == 'TRAJECTOR'] |
| 110 | + landmarks = [t for t in sent.ents if t.label_ == 'LANDMARK'] |
| 111 | + |
| 112 | + # print(trajectors, triggers, landmarks) |
| 113 | + |
| 114 | + for trigger in triggers: |
| 115 | + for trajector in trajectors: |
| 116 | + for landmark in landmarks: |
| 117 | + if not (trajector is None and landmark is None): |
| 118 | + assert trajector.sent == trigger.sent == landmark.sent, "{}: {}".format(sent, sent.ents) |
| 119 | + crel = (trajector, trigger, landmark) |
| 120 | + if crel not in gold_relations: |
| 121 | + candidate_relations.append(crel) |
| 122 | + candidate_labels.append('NONE') |
| 123 | + else: |
| 124 | + #print("In gold relations already", crel) |
| 125 | + pass |
| 126 | + return candidate_relations, candidate_labels |
| 127 | + |
| 128 | +def sprl(sentence, |
| 129 | + nlp, |
| 130 | + model_relext_filename='model_svm_relations.pkl'): |
| 131 | + output = [] |
| 132 | + doc = nlp(sentence) |
| 133 | + sents = [nlp(s.text) for s in doc.sents] |
| 134 | + candidate_relations, _ = extract_candidate_relations_from_sents(sents, []) |
| 135 | + clf, dv = joblib.load(model_relext_filename) |
| 136 | + for relation in candidate_relations: |
| 137 | + F = extract_relation_features(relation) |
| 138 | + feat_vec = dv.transform(F) |
| 139 | + general_type = clf.predict(feat_vec)[0] |
| 140 | + if general_type != 'NONE': |
| 141 | + output.append((relation[0], relation[1], relation[2], general_type)) |
| 142 | + |
| 143 | + return output |
| 144 | + |
| 145 | + |
| 146 | +def sprl_str(sentence, |
| 147 | + nlp, |
| 148 | + model_relext_filename='model_svm_relations.pkl'): |
| 149 | + """ Returns triples where every element is string """ |
| 150 | + output = [] |
| 151 | + doc = nlp(sentence) |
| 152 | + sents = [nlp(s.text) for s in doc.sents] |
| 153 | + candidate_relations, _ = extract_candidate_relations_from_sents(sents, []) |
| 154 | + clf, dv = joblib.load(model_relext_filename) |
| 155 | + for relation in candidate_relations: |
| 156 | + F = extract_relation_features(relation) |
| 157 | + feat_vec = dv.transform(F) |
| 158 | + general_type = clf.predict(feat_vec)[0] |
| 159 | + if general_type != 'NONE': |
| 160 | + output.append((str(relation[0]), str(relation[1]), str(relation[2]), general_type)) |
| 161 | + |
| 162 | + return output |
0 commit comments