2017-01-11 12:55:33 +00:00
|
|
|
# coding: utf-8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
|
|
from ..tokens import Doc
|
|
|
|
from ..attrs import ORTH, POS, HEAD, DEP
|
|
|
|
|
2017-01-12 15:49:57 +00:00
|
|
|
import numpy
|
|
|
|
|
2017-01-11 12:55:33 +00:00
|
|
|
|
2017-01-12 11:25:10 +00:00
|
|
|
def get_doc(vocab, words=[], pos=None, heads=None, deps=None, tags=None, ents=None):
|
2017-01-11 12:55:33 +00:00
|
|
|
"""Create Doc object from given vocab, words and annotations."""
|
2017-01-12 10:18:36 +00:00
|
|
|
pos = pos or [''] * len(words)
|
2017-01-11 12:55:33 +00:00
|
|
|
heads = heads or [0] * len(words)
|
|
|
|
deps = deps or [''] * len(words)
|
|
|
|
|
|
|
|
doc = Doc(vocab, words=words)
|
|
|
|
attrs = doc.to_array([POS, HEAD, DEP])
|
2017-01-12 10:18:36 +00:00
|
|
|
for i, (p, head, dep) in enumerate(zip(pos, heads, deps)):
|
|
|
|
attrs[i, 0] = doc.vocab.strings[p]
|
2017-01-11 12:55:33 +00:00
|
|
|
attrs[i, 1] = head
|
|
|
|
attrs[i, 2] = doc.vocab.strings[dep]
|
|
|
|
doc.from_array([POS, HEAD, DEP], attrs)
|
2017-01-12 11:25:10 +00:00
|
|
|
if ents:
|
|
|
|
doc.ents = [(ent_id, doc.vocab.strings[label], start, end) for ent_id, label, start, end in ents]
|
2017-01-12 10:18:36 +00:00
|
|
|
if tags:
|
|
|
|
for token in doc:
|
|
|
|
token.tag_ = tags[token.i]
|
2017-01-11 12:55:33 +00:00
|
|
|
return doc
|
2017-01-11 20:30:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def apply_transition_sequence(parser, doc, sequence):
|
|
|
|
"""Perform a series of pre-specified transitions, to put the parser in a
|
|
|
|
desired state."""
|
|
|
|
for action_name in sequence:
|
|
|
|
if '-' in action_name:
|
|
|
|
move, label = action_name.split('-')
|
|
|
|
parser.add_label(label)
|
|
|
|
with parser.step_through(doc) as stepwise:
|
|
|
|
for transition in sequence:
|
|
|
|
stepwise.transition(transition)
|
2017-01-12 15:49:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_cosine(vec1, vec2):
|
|
|
|
"""Get cosine for two given vectors"""
|
|
|
|
return numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2))
|