partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
get_model_meta
Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data.
spacy/util.py
def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=...
def get_model_meta(path): """Get model meta.json from a directory path and validate its contents. path (unicode or Path): Path to model directory. RETURNS (dict): The model's meta data. """ model_path = ensure_path(path) if not model_path.exists(): raise IOError(Errors.E052.format(path=...
[ "Get", "model", "meta", ".", "json", "from", "a", "directory", "path", "and", "validate", "its", "contents", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L193-L209
[ "def", "get_model_meta", "(", "path", ")", ":", "model_path", "=", "ensure_path", "(", "path", ")", "if", "not", "model_path", ".", "exists", "(", ")", ":", "raise", "IOError", "(", "Errors", ".", "E052", ".", "format", "(", "path", "=", "path2str", "(...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_package_path
Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package.
spacy/util.py
def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it'...
def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it'...
[ "Get", "the", "path", "to", "an", "installed", "package", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L226-L236
[ "def", "get_package_path", "(", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "# use lowercase version to be safe", "# Here we're importing the module just to find it. This is worryingly", "# indirect, but it's otherwise very difficult to find the package.", "pkg", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_entry_points
Get registered entry points from other packages for a given key, e.g. 'spacy_factories' and return them as a dictionary, keyed by name. key (unicode): Entry point name. RETURNS (dict): Entry points, keyed by name.
spacy/util.py
def get_entry_points(key): """Get registered entry points from other packages for a given key, e.g. 'spacy_factories' and return them as a dictionary, keyed by name. key (unicode): Entry point name. RETURNS (dict): Entry points, keyed by name. """ result = {} for entry_point in pkg_resource...
def get_entry_points(key): """Get registered entry points from other packages for a given key, e.g. 'spacy_factories' and return them as a dictionary, keyed by name. key (unicode): Entry point name. RETURNS (dict): Entry points, keyed by name. """ result = {} for entry_point in pkg_resource...
[ "Get", "registered", "entry", "points", "from", "other", "packages", "for", "a", "given", "key", "e", ".", "g", ".", "spacy_factories", "and", "return", "them", "as", "a", "dictionary", "keyed", "by", "name", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L239-L249
[ "def", "get_entry_points", "(", "key", ")", ":", "result", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "key", ")", ":", "result", "[", "entry_point", ".", "name", "]", "=", "entry_point", ".", "load", "(", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_entry_point
Check if registered entry point is available for a given name and load it. Otherwise, return None. key (unicode): Entry point name. value (unicode): Name of entry point to load. RETURNS: The loaded entry point or None.
spacy/util.py
def get_entry_point(key, value): """Check if registered entry point is available for a given name and load it. Otherwise, return None. key (unicode): Entry point name. value (unicode): Name of entry point to load. RETURNS: The loaded entry point or None. """ for entry_point in pkg_resources...
def get_entry_point(key, value): """Check if registered entry point is available for a given name and load it. Otherwise, return None. key (unicode): Entry point name. value (unicode): Name of entry point to load. RETURNS: The loaded entry point or None. """ for entry_point in pkg_resources...
[ "Check", "if", "registered", "entry", "point", "is", "available", "for", "a", "given", "name", "and", "load", "it", ".", "Otherwise", "return", "None", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L252-L262
[ "def", "get_entry_point", "(", "key", ",", "value", ")", ":", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "key", ")", ":", "if", "entry_point", ".", "name", "==", "value", ":", "return", "entry_point", ".", "load", "(", ")" ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
is_in_jupyter
Check if user is running spaCy from a Jupyter notebook by detecting the IPython kernel. Mainly used for the displaCy visualizer. RETURNS (bool): True if in Jupyter, False if not.
spacy/util.py
def is_in_jupyter(): """Check if user is running spaCy from a Jupyter notebook by detecting the IPython kernel. Mainly used for the displaCy visualizer. RETURNS (bool): True if in Jupyter, False if not. """ # https://stackoverflow.com/a/39662359/6400719 try: shell = get_ipython().__class...
def is_in_jupyter(): """Check if user is running spaCy from a Jupyter notebook by detecting the IPython kernel. Mainly used for the displaCy visualizer. RETURNS (bool): True if in Jupyter, False if not. """ # https://stackoverflow.com/a/39662359/6400719 try: shell = get_ipython().__class...
[ "Check", "if", "user", "is", "running", "spaCy", "from", "a", "Jupyter", "notebook", "by", "detecting", "the", "IPython", "kernel", ".", "Mainly", "used", "for", "the", "displaCy", "visualizer", ".", "RETURNS", "(", "bool", ")", ":", "True", "if", "in", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L265-L277
[ "def", "is_in_jupyter", "(", ")", ":", "# https://stackoverflow.com/a/39662359/6400719", "try", ":", "shell", "=", "get_ipython", "(", ")", ".", "__class__", ".", "__name__", "if", "shell", "==", "\"ZMQInteractiveShell\"", ":", "return", "True", "# Jupyter notebook or...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
compile_suffix_regex
Compile a sequence of suffix rules into a regex object. entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
spacy/util.py
def compile_suffix_regex(entries): """Compile a sequence of suffix rules into a regex object. entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search. """ expression = "|".join([piece + "$" f...
def compile_suffix_regex(entries): """Compile a sequence of suffix rules into a regex object. entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search. """ expression = "|".join([piece + "$" f...
[ "Compile", "a", "sequence", "of", "suffix", "rules", "into", "a", "regex", "object", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L346-L353
[ "def", "compile_suffix_regex", "(", "entries", ")", ":", "expression", "=", "\"|\"", ".", "join", "(", "[", "piece", "+", "\"$\"", "for", "piece", "in", "entries", "if", "piece", ".", "strip", "(", ")", "]", ")", "return", "re", ".", "compile", "(", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
compile_infix_regex
Compile a sequence of infix rules into a regex object. entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer.
spacy/util.py
def compile_infix_regex(entries): """Compile a sequence of infix rules into a regex object. entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer. """ expression = "|".join([piece for piece ...
def compile_infix_regex(entries): """Compile a sequence of infix rules into a regex object. entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer. """ expression = "|".join([piece for piece ...
[ "Compile", "a", "sequence", "of", "infix", "rules", "into", "a", "regex", "object", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L356-L363
[ "def", "compile_infix_regex", "(", "entries", ")", ":", "expression", "=", "\"|\"", ".", "join", "(", "[", "piece", "for", "piece", "in", "entries", "if", "piece", ".", "strip", "(", ")", "]", ")", "return", "re", ".", "compile", "(", "expression", ")"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
update_exc
Update and validate tokenizer exceptions. Will overwrite exceptions. base_exceptions (dict): Base exceptions. *addition_dicts (dict): Exceptions to add to the base dict, in order. RETURNS (dict): Combined tokenizer exceptions.
spacy/util.py
def update_exc(base_exceptions, *addition_dicts): """Update and validate tokenizer exceptions. Will overwrite exceptions. base_exceptions (dict): Base exceptions. *addition_dicts (dict): Exceptions to add to the base dict, in order. RETURNS (dict): Combined tokenizer exceptions. """ exc = dict(...
def update_exc(base_exceptions, *addition_dicts): """Update and validate tokenizer exceptions. Will overwrite exceptions. base_exceptions (dict): Base exceptions. *addition_dicts (dict): Exceptions to add to the base dict, in order. RETURNS (dict): Combined tokenizer exceptions. """ exc = dict(...
[ "Update", "and", "validate", "tokenizer", "exceptions", ".", "Will", "overwrite", "exceptions", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L386-L403
[ "def", "update_exc", "(", "base_exceptions", ",", "*", "addition_dicts", ")", ":", "exc", "=", "dict", "(", "base_exceptions", ")", "for", "additions", "in", "addition_dicts", ":", "for", "orth", ",", "token_attrs", "in", "additions", ".", "items", "(", ")",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
expand_exc
Find string in tokenizer exceptions, duplicate entry and replace string. For example, to add additional versions with typographic apostrophes. excs (dict): Tokenizer exceptions. search (unicode): String to find and replace. replace (unicode): Replacement. RETURNS (dict): Combined tokenizer exceptio...
spacy/util.py
def expand_exc(excs, search, replace): """Find string in tokenizer exceptions, duplicate entry and replace string. For example, to add additional versions with typographic apostrophes. excs (dict): Tokenizer exceptions. search (unicode): String to find and replace. replace (unicode): Replacement. ...
def expand_exc(excs, search, replace): """Find string in tokenizer exceptions, duplicate entry and replace string. For example, to add additional versions with typographic apostrophes. excs (dict): Tokenizer exceptions. search (unicode): String to find and replace. replace (unicode): Replacement. ...
[ "Find", "string", "in", "tokenizer", "exceptions", "duplicate", "entry", "and", "replace", "string", ".", "For", "example", "to", "add", "additional", "versions", "with", "typographic", "apostrophes", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L406-L427
[ "def", "expand_exc", "(", "excs", ",", "search", ",", "replace", ")", ":", "def", "_fix_token", "(", "token", ",", "search", ",", "replace", ")", ":", "fixed", "=", "dict", "(", "token", ")", "fixed", "[", "ORTH", "]", "=", "fixed", "[", "ORTH", "]...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
minibatch
Iterate over batches of items. `size` may be an iterator, so that batch-size can vary on each step.
spacy/util.py
def minibatch(items, size=8): """Iterate over batches of items. `size` may be an iterator, so that batch-size can vary on each step. """ if isinstance(size, int): size_ = itertools.repeat(size) else: size_ = size items = iter(items) while True: batch_size = next(size_...
def minibatch(items, size=8): """Iterate over batches of items. `size` may be an iterator, so that batch-size can vary on each step. """ if isinstance(size, int): size_ = itertools.repeat(size) else: size_ = size items = iter(items) while True: batch_size = next(size_...
[ "Iterate", "over", "batches", "of", "items", ".", "size", "may", "be", "an", "iterator", "so", "that", "batch", "-", "size", "can", "vary", "on", "each", "step", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L446-L460
[ "def", "minibatch", "(", "items", ",", "size", "=", "8", ")", ":", "if", "isinstance", "(", "size", ",", "int", ")", ":", "size_", "=", "itertools", ".", "repeat", "(", "size", ")", "else", ":", "size_", "=", "size", "items", "=", "iter", "(", "i...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
compounding
Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert nex...
spacy/util.py
def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> ass...
def compounding(start, stop, compound): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> ass...
[ "Yield", "an", "infinite", "series", "of", "compounding", "values", ".", "Each", "time", "the", "generator", "is", "called", "a", "value", "is", "produced", "by", "multiplying", "the", "previous", "value", "by", "the", "compound", "rate", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L463-L481
[ "def", "compounding", "(", "start", ",", "stop", ",", "compound", ")", ":", "def", "clip", "(", "value", ")", ":", "return", "max", "(", "value", ",", "stop", ")", "if", "(", "start", ">", "stop", ")", "else", "min", "(", "value", ",", "stop", ")...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
stepping
Yield an infinite series of values that step from a start value to a final value over some number of steps. Each step is (stop-start)/steps. After the final value is reached, the generator continues yielding that value. EXAMPLE: >>> sizes = stepping(1., 200., 100) >>> assert next(sizes) ==...
spacy/util.py
def stepping(start, stop, steps): """Yield an infinite series of values that step from a start value to a final value over some number of steps. Each step is (stop-start)/steps. After the final value is reached, the generator continues yielding that value. EXAMPLE: >>> sizes = stepping(1., 2...
def stepping(start, stop, steps): """Yield an infinite series of values that step from a start value to a final value over some number of steps. Each step is (stop-start)/steps. After the final value is reached, the generator continues yielding that value. EXAMPLE: >>> sizes = stepping(1., 2...
[ "Yield", "an", "infinite", "series", "of", "values", "that", "step", "from", "a", "start", "value", "to", "a", "final", "value", "over", "some", "number", "of", "steps", ".", "Each", "step", "is", "(", "stop", "-", "start", ")", "/", "steps", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L484-L504
[ "def", "stepping", "(", "start", ",", "stop", ",", "steps", ")", ":", "def", "clip", "(", "value", ")", ":", "return", "max", "(", "value", ",", "stop", ")", "if", "(", "start", ">", "stop", ")", "else", "min", "(", "value", ",", "stop", ")", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
decaying
Yield an infinite series of linearly decaying values.
spacy/util.py
def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" curr = float(start) while True: yield max(curr, stop) curr -= (decay)
def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" curr = float(start) while True: yield max(curr, stop) curr -= (decay)
[ "Yield", "an", "infinite", "series", "of", "linearly", "decaying", "values", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L507-L513
[ "def", "decaying", "(", "start", ",", "stop", ",", "decay", ")", ":", "curr", "=", "float", "(", "start", ")", "while", "True", ":", "yield", "max", "(", "curr", ",", "stop", ")", "curr", "-=", "(", "decay", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
minibatch_by_words
Create minibatches of a given number of words.
spacy/util.py
def minibatch_by_words(items, size, tuples=True, count_words=len): """Create minibatches of a given number of words.""" if isinstance(size, int): size_ = itertools.repeat(size) else: size_ = size items = iter(items) while True: batch_size = next(size_) batch = [] ...
def minibatch_by_words(items, size, tuples=True, count_words=len): """Create minibatches of a given number of words.""" if isinstance(size, int): size_ = itertools.repeat(size) else: size_ = size items = iter(items) while True: batch_size = next(size_) batch = [] ...
[ "Create", "minibatches", "of", "a", "given", "number", "of", "words", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L516-L542
[ "def", "minibatch_by_words", "(", "items", ",", "size", ",", "tuples", "=", "True", ",", "count_words", "=", "len", ")", ":", "if", "isinstance", "(", "size", ",", "int", ")", ":", "size_", "=", "itertools", ".", "repeat", "(", "size", ")", "else", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
itershuffle
Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 iterable (iterable): Iterator to shuffle. bu...
spacy/util.py
def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 ...
def itershuffle(iterable, bufsize=1000): """Shuffle an iterator. This works by holding `bufsize` items back and yielding them sometime later. Obviously, this is not unbiased – but should be good enough for batching. Larger bufsize means less bias. From https://gist.github.com/andres-erbsen/1307752 ...
[ "Shuffle", "an", "iterator", ".", "This", "works", "by", "holding", "bufsize", "items", "back", "and", "yielding", "them", "sometime", "later", ".", "Obviously", "this", "is", "not", "unbiased", "–", "but", "should", "be", "good", "enough", "for", "batching"...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L545-L571
[ "def", "itershuffle", "(", "iterable", ",", "bufsize", "=", "1000", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "buf", "=", "[", "]", "try", ":", "while", "True", ":", "for", "i", "in", "range", "(", "random", ".", "randint", "(", "1",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
validate_json
Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available.
spacy/util.py
def validate_json(data, validator): """Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available. """ errors = [] for err in...
def validate_json(data, validator): """Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available. """ errors = [] for err in...
[ "Validate", "data", "against", "a", "given", "JSON", "schema", "(", "see", "https", ":", "//", "json", "-", "schema", ".", "org", ")", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L672-L690
[ "def", "validate_json", "(", "data", ",", "validator", ")", ":", "errors", "=", "[", "]", "for", "err", "in", "sorted", "(", "validator", ".", "iter_errors", "(", "data", ")", ",", "key", "=", "lambda", "e", ":", "e", ".", "path", ")", ":", "if", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_serialization_exclude
Helper function to validate serialization args and manage transition from keyword arguments (pre v2.1) to exclude argument.
spacy/util.py
def get_serialization_exclude(serializers, exclude, kwargs): """Helper function to validate serialization args and manage transition from keyword arguments (pre v2.1) to exclude argument. """ exclude = list(exclude) # Split to support file names like meta.json options = [name.split(".")[0] for n...
def get_serialization_exclude(serializers, exclude, kwargs): """Helper function to validate serialization args and manage transition from keyword arguments (pre v2.1) to exclude argument. """ exclude = list(exclude) # Split to support file names like meta.json options = [name.split(".")[0] for n...
[ "Helper", "function", "to", "validate", "serialization", "args", "and", "manage", "transition", "from", "keyword", "arguments", "(", "pre", "v2", ".", "1", ")", "to", "exclude", "argument", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L693-L707
[ "def", "get_serialization_exclude", "(", "serializers", ",", "exclude", ",", "kwargs", ")", ":", "exclude", "=", "list", "(", "exclude", ")", "# Split to support file names like meta.json", "options", "=", "[", "name", ".", "split", "(", "\".\"", ")", "[", "0", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.labels
All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels
spacy/pipeline/entityruler.py
def labels(self): """All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels """ all_labels = set(self.token_patterns.keys()) all_labels.update(self.phrase_patterns.keys()) return tuple(all_labels...
def labels(self): """All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels """ all_labels = set(self.token_patterns.keys()) all_labels.update(self.phrase_patterns.keys()) return tuple(all_labels...
[ "All", "labels", "present", "in", "the", "match", "patterns", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L96-L105
[ "def", "labels", "(", "self", ")", ":", "all_labels", "=", "set", "(", "self", ".", "token_patterns", ".", "keys", "(", ")", ")", "all_labels", ".", "update", "(", "self", ".", "phrase_patterns", ".", "keys", "(", ")", ")", "return", "tuple", "(", "a...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.patterns
Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns
spacy/pipeline/entityruler.py
def patterns(self): """Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns """ all_patterns = [] for label, patterns in self.token_patterns.items(): ...
def patterns(self): """Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns """ all_patterns = [] for label, patterns in self.token_patterns.items(): ...
[ "Get", "all", "patterns", "that", "were", "added", "to", "the", "entity", "ruler", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L108-L122
[ "def", "patterns", "(", "self", ")", ":", "all_patterns", "=", "[", "]", "for", "label", ",", "patterns", "in", "self", ".", "token_patterns", ".", "items", "(", ")", ":", "for", "pattern", "in", "patterns", ":", "all_patterns", ".", "append", "(", "{"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.add_patterns
Add patterns to the entitiy ruler. A pattern can either be a token pattern (list of dicts) or a phrase pattern (string). For example: {'label': 'ORG', 'pattern': 'Apple'} {'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]} patterns (list): The patterns to add. ...
spacy/pipeline/entityruler.py
def add_patterns(self, patterns): """Add patterns to the entitiy ruler. A pattern can either be a token pattern (list of dicts) or a phrase pattern (string). For example: {'label': 'ORG', 'pattern': 'Apple'} {'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]} ...
def add_patterns(self, patterns): """Add patterns to the entitiy ruler. A pattern can either be a token pattern (list of dicts) or a phrase pattern (string). For example: {'label': 'ORG', 'pattern': 'Apple'} {'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]} ...
[ "Add", "patterns", "to", "the", "entitiy", "ruler", ".", "A", "pattern", "can", "either", "be", "a", "token", "pattern", "(", "list", "of", "dicts", ")", "or", "a", "phrase", "pattern", "(", "string", ")", ".", "For", "example", ":", "{", "label", ":...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L124-L146
[ "def", "add_patterns", "(", "self", ",", "patterns", ")", ":", "for", "entry", "in", "patterns", ":", "label", "=", "entry", "[", "\"label\"", "]", "pattern", "=", "entry", "[", "\"pattern\"", "]", "if", "isinstance", "(", "pattern", ",", "basestring_", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.from_bytes
Load the entity ruler from a bytestring. patterns_bytes (bytes): The bytestring to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: https://spacy.io/api/entityruler#from_bytes
spacy/pipeline/entityruler.py
def from_bytes(self, patterns_bytes, **kwargs): """Load the entity ruler from a bytestring. patterns_bytes (bytes): The bytestring to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: https://spacy.io/api/entit...
def from_bytes(self, patterns_bytes, **kwargs): """Load the entity ruler from a bytestring. patterns_bytes (bytes): The bytestring to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: https://spacy.io/api/entit...
[ "Load", "the", "entity", "ruler", "from", "a", "bytestring", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L148-L159
[ "def", "from_bytes", "(", "self", ",", "patterns_bytes", ",", "*", "*", "kwargs", ")", ":", "patterns", "=", "srsly", ".", "msgpack_loads", "(", "patterns_bytes", ")", "self", ".", "add_patterns", "(", "patterns", ")", "return", "self" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.from_disk
Load the entity ruler from a file. Expects a file containing newline-delimited JSON (JSONL) with one entry per line. path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: ht...
spacy/pipeline/entityruler.py
def from_disk(self, path, **kwargs): """Load the entity ruler from a file. Expects a file containing newline-delimited JSON (JSONL) with one entry per line. path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRu...
def from_disk(self, path, **kwargs): """Load the entity ruler from a file. Expects a file containing newline-delimited JSON (JSONL) with one entry per line. path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRu...
[ "Load", "the", "entity", "ruler", "from", "a", "file", ".", "Expects", "a", "file", "containing", "newline", "-", "delimited", "JSON", "(", "JSONL", ")", "with", "one", "entry", "per", "line", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L170-L184
[ "def", "from_disk", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "path", "=", "ensure_path", "(", "path", ")", "path", "=", "path", ".", "with_suffix", "(", "\".jsonl\"", ")", "patterns", "=", "srsly", ".", "read_jsonl", "(", "path", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRuler.to_disk
Save the entity ruler patterns to a directory. The patterns will be saved as newline-delimited JSON (JSONL). path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: https://sp...
spacy/pipeline/entityruler.py
def to_disk(self, path, **kwargs): """Save the entity ruler patterns to a directory. The patterns will be saved as newline-delimited JSON (JSONL). path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The ...
def to_disk(self, path, **kwargs): """Save the entity ruler patterns to a directory. The patterns will be saved as newline-delimited JSON (JSONL). path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The ...
[ "Save", "the", "entity", "ruler", "patterns", "to", "a", "directory", ".", "The", "patterns", "will", "be", "saved", "as", "newline", "-", "delimited", "JSON", "(", "JSONL", ")", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L186-L198
[ "def", "to_disk", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "path", "=", "ensure_path", "(", "path", ")", "path", "=", "path", ".", "with_suffix", "(", "\".jsonl\"", ")", "srsly", ".", "write_jsonl", "(", "path", ",", "self", ".", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
read_data
Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True, include Doc objects created using nlp.make_doc and then aligned against the gold-standard sequences. If oracle_segments=True, include Doc objects created from the gold-standard segments. At least one must be True.
bin/ud/ud_train.py
def read_data( nlp, conllu_file, text_file, raw_text=True, oracle_segments=False, max_doc_length=None, limit=None, ): """Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True, include Doc objects created using nlp.make_doc and then aligned against the gold-standar...
def read_data( nlp, conllu_file, text_file, raw_text=True, oracle_segments=False, max_doc_length=None, limit=None, ): """Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True, include Doc objects created using nlp.make_doc and then aligned against the gold-standar...
[ "Read", "the", "CONLLU", "format", "into", "(", "Doc", "GoldParse", ")", "tuples", ".", "If", "raw_text", "=", "True", "include", "Doc", "objects", "created", "using", "nlp", ".", "make_doc", "and", "then", "aligned", "against", "the", "gold", "-", "standa...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/ud_train.py#L52-L110
[ "def", "read_data", "(", "nlp", ",", "conllu_file", ",", "text_file", ",", "raw_text", "=", "True", ",", "oracle_segments", "=", "False", ",", "max_doc_length", "=", "None", ",", "limit", "=", "None", ",", ")", ":", "if", "not", "raw_text", "and", "not",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
golds_to_gold_tuples
Get out the annoying 'tuples' format used by begin_training, given the GoldParse objects.
bin/ud/ud_train.py
def golds_to_gold_tuples(docs, golds): """Get out the annoying 'tuples' format used by begin_training, given the GoldParse objects.""" tuples = [] for doc, gold in zip(docs, golds): text = doc.text ids, words, tags, heads, labels, iob = zip(*gold.orig_annot) sents = [((ids, words...
def golds_to_gold_tuples(docs, golds): """Get out the annoying 'tuples' format used by begin_training, given the GoldParse objects.""" tuples = [] for doc, gold in zip(docs, golds): text = doc.text ids, words, tags, heads, labels, iob = zip(*gold.orig_annot) sents = [((ids, words...
[ "Get", "out", "the", "annoying", "tuples", "format", "used", "by", "begin_training", "given", "the", "GoldParse", "objects", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/ud_train.py#L173-L182
[ "def", "golds_to_gold_tuples", "(", "docs", ",", "golds", ")", ":", "tuples", "=", "[", "]", "for", "doc", ",", "gold", "in", "zip", "(", "docs", ",", "golds", ")", ":", "text", "=", "doc", ".", "text", "ids", ",", "words", ",", "tags", ",", "hea...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
like_num
check if text resembles a number
spacy/lang/fa/lex_attrs.py
def like_num(text): """ check if text resembles a number """ text = ( text.replace(",", "") .replace(".", "") .replace("،", "") .replace("٫", "") .replace("/", "") ) if text.isdigit(): return True if text in _num_words: return True ...
def like_num(text): """ check if text resembles a number """ text = ( text.replace(",", "") .replace(".", "") .replace("،", "") .replace("٫", "") .replace("/", "") ) if text.isdigit(): return True if text in _num_words: return True ...
[ "check", "if", "text", "resembles", "a", "number" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/fa/lex_attrs.py#L84-L101
[ "def", "like_num", "(", "text", ")", ":", "text", "=", "(", "text", ".", "replace", "(", "\",\"", ",", "\"\"", ")", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ".", "replace", "(", "\"،\",", " ", "\")", "", ".", "replace", "(", "\"٫\",", " ",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
merge_bytes
Concatenate multiple serialized binders into one byte string.
spacy/tokens/_serialize.py
def merge_bytes(binder_strings): """Concatenate multiple serialized binders into one byte string.""" output = None for byte_string in binder_strings: binder = Binder().from_bytes(byte_string) if output is None: output = binder else: output.merge(binder) re...
def merge_bytes(binder_strings): """Concatenate multiple serialized binders into one byte string.""" output = None for byte_string in binder_strings: binder = Binder().from_bytes(byte_string) if output is None: output = binder else: output.merge(binder) re...
[ "Concatenate", "multiple", "serialized", "binders", "into", "one", "byte", "string", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L97-L106
[ "def", "merge_bytes", "(", "binder_strings", ")", ":", "output", "=", "None", "for", "byte_string", "in", "binder_strings", ":", "binder", "=", "Binder", "(", ")", ".", "from_bytes", "(", "byte_string", ")", "if", "output", "is", "None", ":", "output", "="...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Binder.add
Add a doc's annotations to the binder for serialization.
spacy/tokens/_serialize.py
def add(self, doc): """Add a doc's annotations to the binder for serialization.""" array = doc.to_array(self.attrs) if len(array.shape) == 1: array = array.reshape((array.shape[0], 1)) self.tokens.append(array) spaces = doc.to_array(SPACY) assert array.shape[0...
def add(self, doc): """Add a doc's annotations to the binder for serialization.""" array = doc.to_array(self.attrs) if len(array.shape) == 1: array = array.reshape((array.shape[0], 1)) self.tokens.append(array) spaces = doc.to_array(SPACY) assert array.shape[0...
[ "Add", "a", "doc", "s", "annotations", "to", "the", "binder", "for", "serialization", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L35-L45
[ "def", "add", "(", "self", ",", "doc", ")", ":", "array", "=", "doc", ".", "to_array", "(", "self", ".", "attrs", ")", "if", "len", "(", "array", ".", "shape", ")", "==", "1", ":", "array", "=", "array", ".", "reshape", "(", "(", "array", ".", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Binder.get_docs
Recover Doc objects from the annotations, using the given vocab.
spacy/tokens/_serialize.py
def get_docs(self, vocab): """Recover Doc objects from the annotations, using the given vocab.""" for string in self.strings: vocab[string] orth_col = self.attrs.index(ORTH) for tokens, spaces in zip(self.tokens, self.spaces): words = [vocab.strings[orth] for orth...
def get_docs(self, vocab): """Recover Doc objects from the annotations, using the given vocab.""" for string in self.strings: vocab[string] orth_col = self.attrs.index(ORTH) for tokens, spaces in zip(self.tokens, self.spaces): words = [vocab.strings[orth] for orth...
[ "Recover", "Doc", "objects", "from", "the", "annotations", "using", "the", "given", "vocab", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L47-L56
[ "def", "get_docs", "(", "self", ",", "vocab", ")", ":", "for", "string", "in", "self", ".", "strings", ":", "vocab", "[", "string", "]", "orth_col", "=", "self", ".", "attrs", ".", "index", "(", "ORTH", ")", "for", "tokens", ",", "spaces", "in", "z...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Binder.merge
Extend the annotations of this binder with the annotations from another.
spacy/tokens/_serialize.py
def merge(self, other): """Extend the annotations of this binder with the annotations from another.""" assert self.attrs == other.attrs self.tokens.extend(other.tokens) self.spaces.extend(other.spaces) self.strings.update(other.strings)
def merge(self, other): """Extend the annotations of this binder with the annotations from another.""" assert self.attrs == other.attrs self.tokens.extend(other.tokens) self.spaces.extend(other.spaces) self.strings.update(other.strings)
[ "Extend", "the", "annotations", "of", "this", "binder", "with", "the", "annotations", "from", "another", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L58-L63
[ "def", "merge", "(", "self", ",", "other", ")", ":", "assert", "self", ".", "attrs", "==", "other", ".", "attrs", "self", ".", "tokens", ".", "extend", "(", "other", ".", "tokens", ")", "self", ".", "spaces", ".", "extend", "(", "other", ".", "spac...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Binder.to_bytes
Serialize the binder's annotations into a byte string.
spacy/tokens/_serialize.py
def to_bytes(self): """Serialize the binder's annotations into a byte string.""" for tokens in self.tokens: assert len(tokens.shape) == 2, tokens.shape lengths = [len(tokens) for tokens in self.tokens] msg = { "attrs": self.attrs, "tokens": numpy.vstac...
def to_bytes(self): """Serialize the binder's annotations into a byte string.""" for tokens in self.tokens: assert len(tokens.shape) == 2, tokens.shape lengths = [len(tokens) for tokens in self.tokens] msg = { "attrs": self.attrs, "tokens": numpy.vstac...
[ "Serialize", "the", "binder", "s", "annotations", "into", "a", "byte", "string", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L65-L77
[ "def", "to_bytes", "(", "self", ")", ":", "for", "tokens", "in", "self", ".", "tokens", ":", "assert", "len", "(", "tokens", ".", "shape", ")", "==", "2", ",", "tokens", ".", "shape", "lengths", "=", "[", "len", "(", "tokens", ")", "for", "tokens",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Binder.from_bytes
Deserialize the binder's annotations from a byte string.
spacy/tokens/_serialize.py
def from_bytes(self, string): """Deserialize the binder's annotations from a byte string.""" msg = srsly.msgpack_loads(gzip.decompress(string)) self.attrs = msg["attrs"] self.strings = set(msg["strings"]) lengths = numpy.fromstring(msg["lengths"], dtype="int32") flat_spac...
def from_bytes(self, string): """Deserialize the binder's annotations from a byte string.""" msg = srsly.msgpack_loads(gzip.decompress(string)) self.attrs = msg["attrs"] self.strings = set(msg["strings"]) lengths = numpy.fromstring(msg["lengths"], dtype="int32") flat_spac...
[ "Deserialize", "the", "binder", "s", "annotations", "from", "a", "byte", "string", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L79-L94
[ "def", "from_bytes", "(", "self", ",", "string", ")", ":", "msg", "=", "srsly", ".", "msgpack_loads", "(", "gzip", ".", "decompress", "(", "string", ")", ")", "self", ".", "attrs", "=", "msg", "[", "\"attrs\"", "]", "self", ".", "strings", "=", "set"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_data
Load data from the IMDB dataset.
examples/training/train_textcat.py
def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, _ = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) cats = [{"POSITIVE": bool(y...
def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, _ = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) cats = [{"POSITIVE": bool(y...
[ "Load", "data", "from", "the", "IMDB", "dataset", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_textcat.py#L120-L129
[ "def", "load_data", "(", "limit", "=", "0", ",", "split", "=", "0.8", ")", ":", "# Partition off part of the train data for evaluation", "train_data", ",", "_", "=", "thinc", ".", "extra", ".", "datasets", ".", "imdb", "(", ")", "random", ".", "shuffle", "("...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
package
Generate Python package for model data, including meta and required installation files. A new directory will be created in the specified output directory, and model data will be copied over. If --create-meta is set and a meta.json already exists in the output directory, the existing values will be used ...
spacy/cli/package.py
def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False): """ Generate Python package for model data, including meta and required installation files. A new directory will be created in the specified output directory, and model data will be copied over. If --create-meta is s...
def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False): """ Generate Python package for model data, including meta and required installation files. A new directory will be created in the specified output directory, and model data will be copied over. If --create-meta is s...
[ "Generate", "Python", "package", "for", "model", "data", "including", "meta", "and", "required", "installation", "files", ".", "A", "new", "directory", "will", "be", "created", "in", "the", "specified", "output", "directory", "and", "model", "data", "will", "b...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/package.py#L22-L78
[ "def", "package", "(", "input_dir", ",", "output_dir", ",", "meta_path", "=", "None", ",", "create_meta", "=", "False", ",", "force", "=", "False", ")", ":", "msg", "=", "Printer", "(", ")", "input_path", "=", "util", ".", "ensure_path", "(", "input_dir"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
FrenchLemmatizer.is_base_form
Check whether we're dealing with an uninflected paradigm, so we can avoid lemmatization entirely.
spacy/lang/fr/lemmatizer/lemmatizer.py
def is_base_form(self, univ_pos, morphology=None): """ Check whether we're dealing with an uninflected paradigm, so we can avoid lemmatization entirely. """ morphology = {} if morphology is None else morphology others = [key for key in morphology if key ...
def is_base_form(self, univ_pos, morphology=None): """ Check whether we're dealing with an uninflected paradigm, so we can avoid lemmatization entirely. """ morphology = {} if morphology is None else morphology others = [key for key in morphology if key ...
[ "Check", "whether", "we", "re", "dealing", "with", "an", "uninflected", "paradigm", "so", "we", "can", "avoid", "lemmatization", "entirely", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/fr/lemmatizer/lemmatizer.py#L63-L93
[ "def", "is_base_form", "(", "self", ",", "univ_pos", ",", "morphology", "=", "None", ")", ":", "morphology", "=", "{", "}", "if", "morphology", "is", "None", "else", "morphology", "others", "=", "[", "key", "for", "key", "in", "morphology", "if", "key", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
main
Set up the pipeline and entity recognizer, and train the new entity.
examples/training/train_new_entity_type.py
def main(model=None, new_model_name="animal", output_dir=None, n_iter=30): """Set up the pipeline and entity recognizer, and train the new entity.""" random.seed(0) if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: ...
def main(model=None, new_model_name="animal", output_dir=None, n_iter=30): """Set up the pipeline and entity recognizer, and train the new entity.""" random.seed(0) if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: ...
[ "Set", "up", "the", "pipeline", "and", "entity", "recognizer", "and", "train", "the", "new", "entity", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_new_entity_type.py#L71-L134
[ "def", "main", "(", "model", "=", "None", ",", "new_model_name", "=", "\"animal\"", ",", "output_dir", "=", "None", ",", "n_iter", "=", "30", ")", ":", "random", ".", "seed", "(", "0", ")", "if", "model", "is", "not", "None", ":", "nlp", "=", "spac...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
conll_ner2json
Convert files in the CoNLL-2003 NER format into JSON format for use with train cli.
spacy/cli/converters/conll_ner2json.py
def conll_ner2json(input_data, **kwargs): """ Convert files in the CoNLL-2003 NER format into JSON format for use with train cli. """ delimit_docs = "-DOCSTART- -X- O O" output_docs = [] for doc in input_data.strip().split(delimit_docs): doc = doc.strip() if not doc: ...
def conll_ner2json(input_data, **kwargs): """ Convert files in the CoNLL-2003 NER format into JSON format for use with train cli. """ delimit_docs = "-DOCSTART- -X- O O" output_docs = [] for doc in input_data.strip().split(delimit_docs): doc = doc.strip() if not doc: ...
[ "Convert", "files", "in", "the", "CoNLL", "-", "2003", "NER", "format", "into", "JSON", "format", "for", "use", "with", "train", "cli", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/conll_ner2json.py#L7-L38
[ "def", "conll_ner2json", "(", "input_data", ",", "*", "*", "kwargs", ")", ":", "delimit_docs", "=", "\"-DOCSTART- -X- O O\"", "output_docs", "=", "[", "]", "for", "doc", "in", "input_data", ".", "strip", "(", ")", ".", "split", "(", "delimit_docs", ")", ":...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
main
Create a new model, set up the pipeline and train the tagger. In order to train the tagger with a custom tag map, we're creating a new Language instance with a custom vocab.
examples/training/train_tagger.py
def main(lang="en", output_dir=None, n_iter=25): """Create a new model, set up the pipeline and train the tagger. In order to train the tagger with a custom tag map, we're creating a new Language instance with a custom vocab. """ nlp = spacy.blank(lang) # add the tagger to the pipeline # nlp...
def main(lang="en", output_dir=None, n_iter=25): """Create a new model, set up the pipeline and train the tagger. In order to train the tagger with a custom tag map, we're creating a new Language instance with a custom vocab. """ nlp = spacy.blank(lang) # add the tagger to the pipeline # nlp...
[ "Create", "a", "new", "model", "set", "up", "the", "pipeline", "and", "train", "the", "tagger", ".", "In", "order", "to", "train", "the", "tagger", "with", "a", "custom", "tag", "map", "we", "re", "creating", "a", "new", "Language", "instance", "with", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_tagger.py#L47-L89
[ "def", "main", "(", "lang", "=", "\"en\"", ",", "output_dir", "=", "None", ",", "n_iter", "=", "25", ")", ":", "nlp", "=", "spacy", ".", "blank", "(", "lang", ")", "# add the tagger to the pipeline", "# nlp.create_pipe works for built-ins that are registered with sp...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_textcat_data
Load data from the IMDB dataset.
examples/training/pretrain_textcat.py
def load_textcat_data(limit=0): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, eval_data = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) eval_texts, eval_label...
def load_textcat_data(limit=0): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, eval_data = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) eval_texts, eval_label...
[ "Load", "data", "from", "the", "IMDB", "dataset", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/pretrain_textcat.py#L41-L51
[ "def", "load_textcat_data", "(", "limit", "=", "0", ")", ":", "# Partition off part of the train data for evaluation", "train_data", ",", "eval_data", "=", "thinc", ".", "extra", ".", "datasets", ".", "imdb", "(", ")", "random", ".", "shuffle", "(", "train_data", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
init_model
Create a new model from raw data, like word frequencies, Brown clusters and word vectors. If vectors are provided in Word2Vec format, they can be either a .txt or zipped as a .zip or .tar.gz.
spacy/cli/init_model.py
def init_model( lang, output_dir, freqs_loc=None, clusters_loc=None, jsonl_loc=None, vectors_loc=None, prune_vectors=-1, ): """ Create a new model from raw data, like word frequencies, Brown clusters and word vectors. If vectors are provided in Word2Vec format, they can be ei...
def init_model( lang, output_dir, freqs_loc=None, clusters_loc=None, jsonl_loc=None, vectors_loc=None, prune_vectors=-1, ): """ Create a new model from raw data, like word frequencies, Brown clusters and word vectors. If vectors are provided in Word2Vec format, they can be ei...
[ "Create", "a", "new", "model", "from", "raw", "data", "like", "word", "frequencies", "Brown", "clusters", "and", "word", "vectors", ".", "If", "vectors", "are", "provided", "in", "Word2Vec", "format", "they", "can", "be", "either", "a", ".", "txt", "or", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/init_model.py#L39-L91
[ "def", "init_model", "(", "lang", ",", "output_dir", ",", "freqs_loc", "=", "None", ",", "clusters_loc", "=", "None", ",", "jsonl_loc", "=", "None", ",", "vectors_loc", "=", "None", ",", "prune_vectors", "=", "-", "1", ",", ")", ":", "if", "jsonl_loc", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
open_file
Handle .gz, .tar.gz or unzipped files
spacy/cli/init_model.py
def open_file(loc): """Handle .gz, .tar.gz or unzipped files""" loc = ensure_path(loc) if tarfile.is_tarfile(str(loc)): return tarfile.open(str(loc), "r:gz") elif loc.parts[-1].endswith("gz"): return (line.decode("utf8") for line in gzip.open(str(loc), "r")) elif loc.parts[-1].endswi...
def open_file(loc): """Handle .gz, .tar.gz or unzipped files""" loc = ensure_path(loc) if tarfile.is_tarfile(str(loc)): return tarfile.open(str(loc), "r:gz") elif loc.parts[-1].endswith("gz"): return (line.decode("utf8") for line in gzip.open(str(loc), "r")) elif loc.parts[-1].endswi...
[ "Handle", ".", "gz", ".", "tar", ".", "gz", "or", "unzipped", "files" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/init_model.py#L94-L107
[ "def", "open_file", "(", "loc", ")", ":", "loc", "=", "ensure_path", "(", "loc", ")", "if", "tarfile", ".", "is_tarfile", "(", "str", "(", "loc", ")", ")", ":", "return", "tarfile", ".", "open", "(", "str", "(", "loc", ")", ",", "\"r:gz\"", ")", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
main
Load the model, set up the pipeline and train the entity recognizer.
examples/training/train_ner.py
def main(model=None, output_dir=None, n_iter=100): """Load the model, set up the pipeline and train the entity recognizer.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank La...
def main(model=None, output_dir=None, n_iter=100): """Load the model, set up the pipeline and train the entity recognizer.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank La...
[ "Load", "the", "model", "set", "up", "the", "pipeline", "and", "train", "the", "entity", "recognizer", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_ner.py#L34-L99
[ "def", "main", "(", "model", "=", "None", ",", "output_dir", "=", "None", ",", "n_iter", "=", "100", ")", ":", "if", "model", "is", "not", "None", ":", "nlp", "=", "spacy", ".", "load", "(", "model", ")", "# load existing spaCy model", "print", "(", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
pretrain
Pre-train the 'token-to-vector' (tok2vec) layer of pipeline components, using an approximate language-modelling objective. Specifically, we load pre-trained vectors, and train a component like a CNN, BiLSTM, etc to predict vectors which match the pre-trained ones. The weights are saved to a directory af...
spacy/cli/pretrain.py
def pretrain( texts_loc, vectors_model, output_dir, width=96, depth=4, embed_rows=2000, loss_func="cosine", use_vectors=False, dropout=0.2, n_iter=1000, batch_size=3000, max_length=500, min_length=5, seed=0, n_save_every=None, ): """ Pre-train the 'tok...
def pretrain( texts_loc, vectors_model, output_dir, width=96, depth=4, embed_rows=2000, loss_func="cosine", use_vectors=False, dropout=0.2, n_iter=1000, batch_size=3000, max_length=500, min_length=5, seed=0, n_save_every=None, ): """ Pre-train the 'tok...
[ "Pre", "-", "train", "the", "token", "-", "to", "-", "vector", "(", "tok2vec", ")", "layer", "of", "pipeline", "components", "using", "an", "approximate", "language", "-", "modelling", "objective", ".", "Specifically", "we", "load", "pre", "-", "trained", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L40-L161
[ "def", "pretrain", "(", "texts_loc", ",", "vectors_model", ",", "output_dir", ",", "width", "=", "96", ",", "depth", "=", "4", ",", "embed_rows", "=", "2000", ",", "loss_func", "=", "\"cosine\"", ",", "use_vectors", "=", "False", ",", "dropout", "=", "0....
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
make_update
Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss.
spacy/cli/pretrain.py
def make_update(model, docs, optimizer, drop=0.0, objective="L2"): """Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss. """ predictions, backpr...
def make_update(model, docs, optimizer, drop=0.0, objective="L2"): """Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss. """ predictions, backpr...
[ "Perform", "an", "update", "over", "a", "single", "batch", "of", "documents", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L164-L178
[ "def", "make_update", "(", "model", ",", "docs", ",", "optimizer", ",", "drop", "=", "0.0", ",", "objective", "=", "\"L2\"", ")", ":", "predictions", ",", "backprop", "=", "model", ".", "begin_update", "(", "docs", ",", "drop", "=", "drop", ")", "loss"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_vectors_loss
Compute a mean-squared error loss between the documents' vectors and the prediction. Note that this is ripe for customization! We could compute the vectors in some other word, e.g. with an LSTM language model, or use some other type of objective.
spacy/cli/pretrain.py
def get_vectors_loss(ops, docs, prediction, objective="L2"): """Compute a mean-squared error loss between the documents' vectors and the prediction. Note that this is ripe for customization! We could compute the vectors in some other word, e.g. with an LSTM language model, or use some other type of...
def get_vectors_loss(ops, docs, prediction, objective="L2"): """Compute a mean-squared error loss between the documents' vectors and the prediction. Note that this is ripe for customization! We could compute the vectors in some other word, e.g. with an LSTM language model, or use some other type of...
[ "Compute", "a", "mean", "-", "squared", "error", "loss", "between", "the", "documents", "vectors", "and", "the", "prediction", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L199-L218
[ "def", "get_vectors_loss", "(", "ops", ",", "docs", ",", "prediction", ",", "objective", "=", "\"L2\"", ")", ":", "# The simplest way to implement this would be to vstack the", "# token.vector values, but that's a bit inefficient, especially on GPU.", "# Instead we fetch the index in...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
create_pretraining_model
Define a network for the pretraining. We simply add an output layer onto the tok2vec input model. The tok2vec input model needs to be a model that takes a batch of Doc objects (as a list), and returns a list of arrays. Each array in the output needs to have one row per token in the doc.
spacy/cli/pretrain.py
def create_pretraining_model(nlp, tok2vec): """Define a network for the pretraining. We simply add an output layer onto the tok2vec input model. The tok2vec input model needs to be a model that takes a batch of Doc objects (as a list), and returns a list of arrays. Each array in the output needs to have...
def create_pretraining_model(nlp, tok2vec): """Define a network for the pretraining. We simply add an output layer onto the tok2vec input model. The tok2vec input model needs to be a model that takes a batch of Doc objects (as a list), and returns a list of arrays. Each array in the output needs to have...
[ "Define", "a", "network", "for", "the", "pretraining", ".", "We", "simply", "add", "an", "output", "layer", "onto", "the", "tok2vec", "input", "model", ".", "The", "tok2vec", "input", "model", "needs", "to", "be", "a", "model", "that", "takes", "a", "bat...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L236-L256
[ "def", "create_pretraining_model", "(", "nlp", ",", "tok2vec", ")", ":", "output_size", "=", "nlp", ".", "vocab", ".", "vectors", ".", "data", ".", "shape", "[", "1", "]", "output_layer", "=", "chain", "(", "LN", "(", "Maxout", "(", "300", ",", "pieces...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
_smart_round
Round large numbers as integers, smaller numbers as decimals.
spacy/cli/pretrain.py
def _smart_round(figure, width=10, max_decimal=4): """Round large numbers as integers, smaller numbers as decimals.""" n_digits = len(str(int(figure))) n_decimal = width - (n_digits + 1) if n_decimal <= 1: return str(int(figure)) else: n_decimal = min(n_decimal, max_decimal) ...
def _smart_round(figure, width=10, max_decimal=4): """Round large numbers as integers, smaller numbers as decimals.""" n_digits = len(str(int(figure))) n_decimal = width - (n_digits + 1) if n_decimal <= 1: return str(int(figure)) else: n_decimal = min(n_decimal, max_decimal) ...
[ "Round", "large", "numbers", "as", "integers", "smaller", "numbers", "as", "decimals", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L295-L304
[ "def", "_smart_round", "(", "figure", ",", "width", "=", "10", ",", "max_decimal", "=", "4", ")", ":", "n_digits", "=", "len", "(", "str", "(", "int", "(", "figure", ")", ")", ")", "n_decimal", "=", "width", "-", "(", "n_digits", "+", "1", ")", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
noun_chunks
Detect base noun phrases. Works on both Doc and Span.
spacy/lang/el/syntax_iterators.py
def noun_chunks(obj): """ Detect base noun phrases. Works on both Doc and Span. """ # It follows the logic of the noun chunks finder of English language, # adjusted to some Greek language special characteristics. # obj tag corrects some DEP tagger mistakes. # Further improvement of the model...
def noun_chunks(obj): """ Detect base noun phrases. Works on both Doc and Span. """ # It follows the logic of the noun chunks finder of English language, # adjusted to some Greek language special characteristics. # obj tag corrects some DEP tagger mistakes. # Further improvement of the model...
[ "Detect", "base", "noun", "phrases", ".", "Works", "on", "both", "Doc", "and", "Span", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/el/syntax_iterators.py#L7-L55
[ "def", "noun_chunks", "(", "obj", ")", ":", "# It follows the logic of the noun chunks finder of English language,", "# adjusted to some Greek language special characteristics.", "# obj tag corrects some DEP tagger mistakes.", "# Further improvement of the models will eliminate the need for this t...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_ext_args
Validate and convert arguments. Reused in Doc, Token and Span.
spacy/tokens/underscore.py
def get_ext_args(**kwargs): """Validate and convert arguments. Reused in Doc, Token and Span.""" default = kwargs.get("default") getter = kwargs.get("getter") setter = kwargs.get("setter") method = kwargs.get("method") if getter is None and setter is not None: raise ValueError(Errors.E08...
def get_ext_args(**kwargs): """Validate and convert arguments. Reused in Doc, Token and Span.""" default = kwargs.get("default") getter = kwargs.get("getter") setter = kwargs.get("setter") method = kwargs.get("method") if getter is None and setter is not None: raise ValueError(Errors.E08...
[ "Validate", "and", "convert", "arguments", ".", "Reused", "in", "Doc", "Token", "and", "Span", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/underscore.py#L69-L87
[ "def", "get_ext_args", "(", "*", "*", "kwargs", ")", ":", "default", "=", "kwargs", ".", "get", "(", "\"default\"", ")", "getter", "=", "kwargs", ".", "get", "(", "\"getter\"", ")", "setter", "=", "kwargs", ".", "get", "(", "\"setter\"", ")", "method",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
is_writable_attr
Check if an extension attribute is writable. ext (tuple): The (default, getter, setter, method) tuple available via {Doc,Span,Token}.get_extension. RETURNS (bool): Whether the attribute is writable.
spacy/tokens/underscore.py
def is_writable_attr(ext): """Check if an extension attribute is writable. ext (tuple): The (default, getter, setter, method) tuple available via {Doc,Span,Token}.get_extension. RETURNS (bool): Whether the attribute is writable. """ default, method, getter, setter = ext # Extension is w...
def is_writable_attr(ext): """Check if an extension attribute is writable. ext (tuple): The (default, getter, setter, method) tuple available via {Doc,Span,Token}.get_extension. RETURNS (bool): Whether the attribute is writable. """ default, method, getter, setter = ext # Extension is w...
[ "Check", "if", "an", "extension", "attribute", "is", "writable", ".", "ext", "(", "tuple", ")", ":", "The", "(", "default", "getter", "setter", "method", ")", "tuple", "available", "via", "{", "Doc", "Span", "Token", "}", ".", "get_extension", ".", "RETU...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/underscore.py#L90-L102
[ "def", "is_writable_attr", "(", "ext", ")", ":", "default", ",", "method", ",", "getter", ",", "setter", "=", "ext", "# Extension is writable if it has a setter (getter + setter), if it has a", "# default value (or, if its default value is none, none of the other values", "# should...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
is_new_osx
Check whether we're on OSX >= 10.10
setup.py
def is_new_osx(): """Check whether we're on OSX >= 10.10""" name = distutils.util.get_platform() if sys.platform != "darwin": return False elif name.startswith("macosx-10"): minor_version = int(name.split("-")[1].split(".")[1]) if minor_version >= 7: return True ...
def is_new_osx(): """Check whether we're on OSX >= 10.10""" name = distutils.util.get_platform() if sys.platform != "darwin": return False elif name.startswith("macosx-10"): minor_version = int(name.split("-")[1].split(".")[1]) if minor_version >= 7: return True ...
[ "Check", "whether", "we", "re", "on", "OSX", ">", "=", "10", ".", "10" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/setup.py#L15-L27
[ "def", "is_new_osx", "(", ")", ":", "name", "=", "distutils", ".", "util", ".", "get_platform", "(", ")", "if", "sys", ".", "platform", "!=", "\"darwin\"", ":", "return", "False", "elif", "name", ".", "startswith", "(", "\"macosx-10\"", ")", ":", "minor_...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_position_label
Return labels indicating the position of the word in the document.
examples/training/ner_multitask_objective.py
def get_position_label(i, words, tags, heads, labels, ents): """Return labels indicating the position of the word in the document. """ if len(words) < 20: return "short-doc" elif i == 0: return "first-word" elif i < 10: return "early-word" elif i < 20: return "mid...
def get_position_label(i, words, tags, heads, labels, ents): """Return labels indicating the position of the word in the document. """ if len(words) < 20: return "short-doc" elif i == 0: return "first-word" elif i < 10: return "early-word" elif i < 20: return "mid...
[ "Return", "labels", "indicating", "the", "position", "of", "the", "word", "in", "the", "document", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/ner_multitask_objective.py#L36-L50
[ "def", "get_position_label", "(", "i", ",", "words", ",", "tags", ",", "heads", ",", "labels", ",", "ents", ")", ":", "if", "len", "(", "words", ")", "<", "20", ":", "return", "\"short-doc\"", "elif", "i", "==", "0", ":", "return", "\"first-word\"", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
download
Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version. For direct downloads, the compatibility check will be skipped.
spacy/cli/download.py
def download(model, direct=False, *pip_args): """ Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version. For direct downloads, the compatibility check will be skipped. """ dl_tpl = "{m}-{v}/{m}-...
def download(model, direct=False, *pip_args): """ Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version. For direct downloads, the compatibility check will be skipped. """ dl_tpl = "{m}-{v}/{m}-...
[ "Download", "compatible", "model", "from", "default", "download", "path", "using", "pip", ".", "Model", "can", "be", "shortcut", "model", "name", "or", "if", "--", "direct", "flag", "is", "set", "full", "model", "name", "with", "version", ".", "For", "dire...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/download.py#L24-L69
[ "def", "download", "(", "model", ",", "direct", "=", "False", ",", "*", "pip_args", ")", ":", "dl_tpl", "=", "\"{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}\"", "if", "direct", ":", "components", "=", "model", ".", "split", "(", "\"-\"", ")", "model_name", "=", "\"\"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
convert
Convert files into JSON format for use with train command and other experiment management functions. If no output_dir is specified, the data is written to stdout, so you can pipe them forward to a JSON file: $ spacy convert some_file.conllu > some_file.json
spacy/cli/convert.py
def convert( input_file, output_dir="-", file_type="json", n_sents=1, morphology=False, converter="auto", lang=None, ): """ Convert files into JSON format for use with train command and other experiment management functions. If no output_dir is specified, the data is written ...
def convert( input_file, output_dir="-", file_type="json", n_sents=1, morphology=False, converter="auto", lang=None, ): """ Convert files into JSON format for use with train command and other experiment management functions. If no output_dir is specified, the data is written ...
[ "Convert", "files", "into", "JSON", "format", "for", "use", "with", "train", "command", "and", "other", "experiment", "management", "functions", ".", "If", "no", "output_dir", "is", "specified", "the", "data", "is", "written", "to", "stdout", "so", "you", "c...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/convert.py#L39-L97
[ "def", "convert", "(", "input_file", ",", "output_dir", "=", "\"-\"", ",", "file_type", "=", "\"json\"", ",", "n_sents", "=", "1", ",", "morphology", "=", "False", ",", "converter", "=", "\"auto\"", ",", "lang", "=", "None", ",", ")", ":", "msg", "=", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model
Load a specific spaCy model
bin/ud/run_eval.py
def load_model(modelname, add_sentencizer=False): """ Load a specific spaCy model """ loading_start = time.time() nlp = spacy.load(modelname) if add_sentencizer: nlp.add_pipe(nlp.create_pipe('sentencizer')) loading_end = time.time() loading_time = loading_end - loading_start if add_s...
def load_model(modelname, add_sentencizer=False): """ Load a specific spaCy model """ loading_start = time.time() nlp = spacy.load(modelname) if add_sentencizer: nlp.add_pipe(nlp.create_pipe('sentencizer')) loading_end = time.time() loading_time = loading_end - loading_start if add_s...
[ "Load", "a", "specific", "spaCy", "model" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L34-L44
[ "def", "load_model", "(", "modelname", ",", "add_sentencizer", "=", "False", ")", ":", "loading_start", "=", "time", ".", "time", "(", ")", "nlp", "=", "spacy", ".", "load", "(", "modelname", ")", "if", "add_sentencizer", ":", "nlp", ".", "add_pipe", "("...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_default_model_sentencizer
Load a generic spaCy model and add the sentencizer for sentence tokenization
bin/ud/run_eval.py
def load_default_model_sentencizer(lang): """ Load a generic spaCy model and add the sentencizer for sentence tokenization""" loading_start = time.time() lang_class = get_lang_class(lang) nlp = lang_class() nlp.add_pipe(nlp.create_pipe('sentencizer')) loading_end = time.time() loading_time =...
def load_default_model_sentencizer(lang): """ Load a generic spaCy model and add the sentencizer for sentence tokenization""" loading_start = time.time() lang_class = get_lang_class(lang) nlp = lang_class() nlp.add_pipe(nlp.create_pipe('sentencizer')) loading_end = time.time() loading_time =...
[ "Load", "a", "generic", "spaCy", "model", "and", "add", "the", "sentencizer", "for", "sentence", "tokenization" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L47-L55
[ "def", "load_default_model_sentencizer", "(", "lang", ")", ":", "loading_start", "=", "time", ".", "time", "(", ")", "lang_class", "=", "get_lang_class", "(", "lang", ")", "nlp", "=", "lang_class", "(", ")", "nlp", ".", "add_pipe", "(", "nlp", ".", "create...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_freq_tuples
Turn a list of errors into frequency-sorted tuples thresholded by a certain total number
bin/ud/run_eval.py
def get_freq_tuples(my_list, print_total_threshold): """ Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """ d = {} for token in my_list: d.setdefault(token, 0) d[token] += 1 return sorted(d.items(), key=operator.itemgetter(1), reverse=True)[:prin...
def get_freq_tuples(my_list, print_total_threshold): """ Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """ d = {} for token in my_list: d.setdefault(token, 0) d[token] += 1 return sorted(d.items(), key=operator.itemgetter(1), reverse=True)[:prin...
[ "Turn", "a", "list", "of", "errors", "into", "frequency", "-", "sorted", "tuples", "thresholded", "by", "a", "certain", "total", "number" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L62-L68
[ "def", "get_freq_tuples", "(", "my_list", ",", "print_total_threshold", ")", ":", "d", "=", "{", "}", "for", "token", "in", "my_list", ":", "d", ".", "setdefault", "(", "token", ",", "0", ")", "d", "[", "token", "]", "+=", "1", "return", "sorted", "(...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
_contains_blinded_text
Heuristic to determine whether the treebank has blinded texts or not
bin/ud/run_eval.py
def _contains_blinded_text(stats_xml): """ Heuristic to determine whether the treebank has blinded texts or not """ tree = ET.parse(stats_xml) root = tree.getroot() total_tokens = int(root.find('size/total/tokens').text) unique_lemmas = int(root.find('lemmas').get('unique')) # assume the corpus...
def _contains_blinded_text(stats_xml): """ Heuristic to determine whether the treebank has blinded texts or not """ tree = ET.parse(stats_xml) root = tree.getroot() total_tokens = int(root.find('size/total/tokens').text) unique_lemmas = int(root.find('lemmas').get('unique')) # assume the corpus...
[ "Heuristic", "to", "determine", "whether", "the", "treebank", "has", "blinded", "texts", "or", "not" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L71-L79
[ "def", "_contains_blinded_text", "(", "stats_xml", ")", ":", "tree", "=", "ET", ".", "parse", "(", "stats_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")", "total_tokens", "=", "int", "(", "root", ".", "find", "(", "'size/total/tokens'", ")", "."...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
fetch_all_treebanks
Fetch the txt files for all treebanks for a given set of languages
bin/ud/run_eval.py
def fetch_all_treebanks(ud_dir, languages, corpus, best_per_language): """" Fetch the txt files for all treebanks for a given set of languages """ all_treebanks = dict() treebank_size = dict() for l in languages: all_treebanks[l] = [] treebank_size[l] = 0 for treebank_dir in ud_dir....
def fetch_all_treebanks(ud_dir, languages, corpus, best_per_language): """" Fetch the txt files for all treebanks for a given set of languages """ all_treebanks = dict() treebank_size = dict() for l in languages: all_treebanks[l] = [] treebank_size[l] = 0 for treebank_dir in ud_dir....
[ "Fetch", "the", "txt", "files", "for", "all", "treebanks", "for", "a", "given", "set", "of", "languages" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L82-L111
[ "def", "fetch_all_treebanks", "(", "ud_dir", ",", "languages", ",", "corpus", ",", "best_per_language", ")", ":", "all_treebanks", "=", "dict", "(", ")", "treebank_size", "=", "dict", "(", ")", "for", "l", "in", "languages", ":", "all_treebanks", "[", "l", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
run_single_eval
Run an evaluation of a model nlp on a certain specified treebank
bin/ud/run_eval.py
def run_single_eval(nlp, loading_time, print_name, text_path, gold_ud, tmp_output_path, out_file, print_header, check_parse, print_freq_tasks): """" Run an evaluation of a model nlp on a certain specified treebank """ with text_path.open(mode='r', encoding='utf-8') as f: flat_text = ...
def run_single_eval(nlp, loading_time, print_name, text_path, gold_ud, tmp_output_path, out_file, print_header, check_parse, print_freq_tasks): """" Run an evaluation of a model nlp on a certain specified treebank """ with text_path.open(mode='r', encoding='utf-8') as f: flat_text = ...
[ "Run", "an", "evaluation", "of", "a", "model", "nlp", "on", "a", "certain", "specified", "treebank" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L114-L181
[ "def", "run_single_eval", "(", "nlp", ",", "loading_time", ",", "print_name", ",", "text_path", ",", "gold_ud", ",", "tmp_output_path", ",", "out_file", ",", "print_header", ",", "check_parse", ",", "print_freq_tasks", ")", ":", "with", "text_path", ".", "open",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
run_all_evals
Run an evaluation for each language with its specified models and treebanks
bin/ud/run_eval.py
def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks): """" Run an evaluation for each language with its specified models and treebanks """ print_header = True for tb_lang, treebank_list in treebanks.items(): print() print("Language", tb_lang) for text_path i...
def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks): """" Run an evaluation for each language with its specified models and treebanks """ print_header = True for tb_lang, treebank_list in treebanks.items(): print() print("Language", tb_lang) for text_path i...
[ "Run", "an", "evaluation", "for", "each", "language", "with", "its", "specified", "models", "and", "treebanks" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L184-L212
[ "def", "run_all_evals", "(", "models", ",", "treebanks", ",", "out_file", ",", "check_parse", ",", "print_freq_tasks", ")", ":", "print_header", "=", "True", "for", "tb_lang", ",", "treebank_list", "in", "treebanks", ".", "items", "(", ")", ":", "print", "("...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
main
Assemble all treebanks and models to run evaluations with. When setting check_parse to True, the default models will not be evaluated as they don't have parsing functionality
bin/ud/run_eval.py
def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False, hide_freq=False, corpus='train', best_per_language=False): """" Assemble all treebanks and models to run evaluations with. When setting check_parse to True, the default models will ...
def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False, hide_freq=False, corpus='train', best_per_language=False): """" Assemble all treebanks and models to run evaluations with. When setting check_parse to True, the default models will ...
[ "Assemble", "all", "treebanks", "and", "models", "to", "run", "evaluations", "with", ".", "When", "setting", "check_parse", "to", "True", "the", "default", "models", "will", "not", "be", "evaluated", "as", "they", "don", "t", "have", "parsing", "functionality"...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L226-L283
[ "def", "main", "(", "out_path", ",", "ud_dir", ",", "check_parse", "=", "False", ",", "langs", "=", "ALL_LANGUAGES", ",", "exclude_trained_models", "=", "False", ",", "exclude_multi", "=", "False", ",", "hide_freq", "=", "False", ",", "corpus", "=", "'train'...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
noun_chunks
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
spacy/lang/de/syntax_iterators.py
def noun_chunks(obj): """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # this iterator extracts spans headed by NOUNs starting from the left-most # syntactic dependent until the NOUN itself for close apposition and # measurement construction, the span is some...
def noun_chunks(obj): """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # this iterator extracts spans headed by NOUNs starting from the left-most # syntactic dependent until the NOUN itself for close apposition and # measurement construction, the span is some...
[ "Detect", "base", "noun", "phrases", "from", "a", "dependency", "parse", ".", "Works", "on", "both", "Doc", "and", "Span", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/de/syntax_iterators.py#L7-L46
[ "def", "noun_chunks", "(", "obj", ")", ":", "# this iterator extracts spans headed by NOUNs starting from the left-most", "# syntactic dependent until the NOUN itself for close apposition and", "# measurement construction, the span is sometimes extended to the right of", "# the NOUN. Example: \"ei...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
with_cpu
Wrap a model that should run on CPU, transferring inputs and outputs as necessary.
spacy/_ml.py
def with_cpu(ops, model): """Wrap a model that should run on CPU, transferring inputs and outputs as necessary.""" model.to_cpu() def with_cpu_forward(inputs, drop=0.0): cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop) gpu_outputs = _to_device(ops, cpu_outputs) ...
def with_cpu(ops, model): """Wrap a model that should run on CPU, transferring inputs and outputs as necessary.""" model.to_cpu() def with_cpu_forward(inputs, drop=0.0): cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop) gpu_outputs = _to_device(ops, cpu_outputs) ...
[ "Wrap", "a", "model", "that", "should", "run", "on", "CPU", "transferring", "inputs", "and", "outputs", "as", "necessary", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L84-L99
[ "def", "with_cpu", "(", "ops", ",", "model", ")", ":", "model", ".", "to_cpu", "(", ")", "def", "with_cpu_forward", "(", "inputs", ",", "drop", "=", "0.0", ")", ":", "cpu_outputs", ",", "backprop", "=", "model", ".", "begin_update", "(", "_to_cpu", "("...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
build_simple_cnn_text_classifier
Build a simple CNN text classifier, given a token-to-vector model as inputs. If exclusive_classes=True, a softmax non-linearity is applied, so that the outputs sum to 1. If exclusive_classes=False, a logistic non-linearity is applied instead, so that outputs are in the range [0, 1].
spacy/_ml.py
def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg): """ Build a simple CNN text classifier, given a token-to-vector model as inputs. If exclusive_classes=True, a softmax non-linearity is applied, so that the outputs sum to 1. If exclusive_classes=False, a logistic no...
def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg): """ Build a simple CNN text classifier, given a token-to-vector model as inputs. If exclusive_classes=True, a softmax non-linearity is applied, so that the outputs sum to 1. If exclusive_classes=False, a logistic no...
[ "Build", "a", "simple", "CNN", "text", "classifier", "given", "a", "token", "-", "to", "-", "vector", "model", "as", "inputs", ".", "If", "exclusive_classes", "=", "True", "a", "softmax", "non", "-", "linearity", "is", "applied", "so", "that", "the", "ou...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L635-L652
[ "def", "build_simple_cnn_text_classifier", "(", "tok2vec", ",", "nr_class", ",", "exclusive_classes", "=", "False", ",", "*", "*", "cfg", ")", ":", "with", "Model", ".", "define_operators", "(", "{", "\">>\"", ":", "chain", "}", ")", ":", "if", "exclusive_cl...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
concatenate_lists
Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`
spacy/_ml.py
def concatenate_lists(*layers, **kwargs): # pragma: no cover """Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))` """ if not layers: return noop() drop_factor = kwargs.get("drop_factor", 1.0) ops...
def concatenate_lists(*layers, **kwargs): # pragma: no cover """Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))` """ if not layers: return noop() drop_factor = kwargs.get("drop_factor", 1.0) ops...
[ "Compose", "two", "or", "more", "models", "f", "g", "etc", "such", "that", "their", "outputs", "are", "concatenated", "i", ".", "e", ".", "concatenate", "(", "f", "g", ")", "(", "x", ")", "computes", "hstack", "(", "f", "(", "x", ")", "g", "(", "...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L667-L690
[ "def", "concatenate_lists", "(", "*", "layers", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "if", "not", "layers", ":", "return", "noop", "(", ")", "drop_factor", "=", "kwargs", ".", "get", "(", "\"drop_factor\"", ",", "1.0", ")", "ops", "="...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
masked_language_model
Convert a model into a BERT-style masked language model
spacy/_ml.py
def masked_language_model(vocab, model, mask_prob=0.15): """Convert a model into a BERT-style masked language model""" random_words = _RandomWords(vocab) def mlm_forward(docs, drop=0.0): mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob) mask = model.ops.asarray(mask).reshap...
def masked_language_model(vocab, model, mask_prob=0.15): """Convert a model into a BERT-style masked language model""" random_words = _RandomWords(vocab) def mlm_forward(docs, drop=0.0): mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob) mask = model.ops.asarray(mask).reshap...
[ "Convert", "a", "model", "into", "a", "BERT", "-", "style", "masked", "language", "model" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L693-L709
[ "def", "masked_language_model", "(", "vocab", ",", "model", ",", "mask_prob", "=", "0.15", ")", ":", "random_words", "=", "_RandomWords", "(", "vocab", ")", "def", "mlm_forward", "(", "docs", ",", "drop", "=", "0.0", ")", ":", "mask", ",", "docs", "=", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
SimilarityHook.begin_training
Allocate model, using width from tensorizer in pipeline. gold_tuples (iterable): Gold-standard training data. pipeline (list): The pipeline the model is part of.
spacy/pipeline/hooks.py
def begin_training(self, _=tuple(), pipeline=None, sgd=None, **kwargs): """Allocate model, using width from tensorizer in pipeline. gold_tuples (iterable): Gold-standard training data. pipeline (list): The pipeline the model is part of. """ if self.model is True: sel...
def begin_training(self, _=tuple(), pipeline=None, sgd=None, **kwargs): """Allocate model, using width from tensorizer in pipeline. gold_tuples (iterable): Gold-standard training data. pipeline (list): The pipeline the model is part of. """ if self.model is True: sel...
[ "Allocate", "model", "using", "width", "from", "tensorizer", "in", "pipeline", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/hooks.py#L89-L100
[ "def", "begin_training", "(", "self", ",", "_", "=", "tuple", "(", ")", ",", "pipeline", "=", "None", ",", "sgd", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "model", "is", "True", ":", "self", ".", "model", "=", "self", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.render
Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered SVG or HTML markup.
spacy/displacy/render.py
def render(self, parsed, page=False, minify=False): """Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered SVG or HTML markup. """ ...
def render(self, parsed, page=False, minify=False): """Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered SVG or HTML markup. """ ...
[ "Render", "complete", "markup", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L39-L68
[ "def", "render", "(", "self", ",", "parsed", ",", "page", "=", "False", ",", "minify", "=", "False", ")", ":", "# Create a random ID prefix to make sure parses don't receive the", "# same ID, even if they're identical", "id_prefix", "=", "uuid", ".", "uuid4", "(", ")"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.render_svg
Render SVG. render_id (int): Unique ID, typically index of document. words (list): Individual words and their tags. arcs (list): Individual arcs and their start, end, direction and label. RETURNS (unicode): Rendered SVG markup.
spacy/displacy/render.py
def render_svg(self, render_id, words, arcs): """Render SVG. render_id (int): Unique ID, typically index of document. words (list): Individual words and their tags. arcs (list): Individual arcs and their start, end, direction and label. RETURNS (unicode): Rendered SVG markup. ...
def render_svg(self, render_id, words, arcs): """Render SVG. render_id (int): Unique ID, typically index of document. words (list): Individual words and their tags. arcs (list): Individual arcs and their start, end, direction and label. RETURNS (unicode): Rendered SVG markup. ...
[ "Render", "SVG", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L70-L100
[ "def", "render_svg", "(", "self", ",", "render_id", ",", "words", ",", "arcs", ")", ":", "self", ".", "levels", "=", "self", ".", "get_levels", "(", "arcs", ")", "self", ".", "highest_level", "=", "len", "(", "self", ".", "levels", ")", "self", ".", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.render_word
Render individual word. text (unicode): Word text. tag (unicode): Part-of-speech tag. i (int): Unique ID, typically word index. RETURNS (unicode): Rendered SVG markup.
spacy/displacy/render.py
def render_word(self, text, tag, i): """Render individual word. text (unicode): Word text. tag (unicode): Part-of-speech tag. i (int): Unique ID, typically word index. RETURNS (unicode): Rendered SVG markup. """ y = self.offset_y + self.word_spacing x = s...
def render_word(self, text, tag, i): """Render individual word. text (unicode): Word text. tag (unicode): Part-of-speech tag. i (int): Unique ID, typically word index. RETURNS (unicode): Rendered SVG markup. """ y = self.offset_y + self.word_spacing x = s...
[ "Render", "individual", "word", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L102-L115
[ "def", "render_word", "(", "self", ",", "text", ",", "tag", ",", "i", ")", ":", "y", "=", "self", ".", "offset_y", "+", "self", ".", "word_spacing", "x", "=", "self", ".", "offset_x", "+", "i", "*", "self", ".", "distance", "if", "self", ".", "di...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.render_arrow
Render individual arrow. label (unicode): Dependency label. start (int): Index of start word. end (int): Index of end word. direction (unicode): Arrow direction, 'left' or 'right'. i (int): Unique ID, typically arrow index. RETURNS (unicode): Rendered SVG markup.
spacy/displacy/render.py
def render_arrow(self, label, start, end, direction, i): """Render individual arrow. label (unicode): Dependency label. start (int): Index of start word. end (int): Index of end word. direction (unicode): Arrow direction, 'left' or 'right'. i (int): Unique ID, typically ...
def render_arrow(self, label, start, end, direction, i): """Render individual arrow. label (unicode): Dependency label. start (int): Index of start word. end (int): Index of end word. direction (unicode): Arrow direction, 'left' or 'right'. i (int): Unique ID, typically ...
[ "Render", "individual", "arrow", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L117-L156
[ "def", "render_arrow", "(", "self", ",", "label", ",", "start", ",", "end", ",", "direction", ",", "i", ")", ":", "level", "=", "self", ".", "levels", ".", "index", "(", "end", "-", "start", ")", "+", "1", "x_start", "=", "self", ".", "offset_x", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.get_arc
Render individual arc. x_start (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. y_curve (int): Y-corrdinate of Cubic Bézier y_curve point. x_end (int): X-coordinate of arrow end point. RETURNS (unicode): Definition of the arc path ('d...
spacy/displacy/render.py
def get_arc(self, x_start, y, y_curve, x_end): """Render individual arc. x_start (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. y_curve (int): Y-corrdinate of Cubic Bézier y_curve point. x_end (int): X-coordinate of arrow end point....
def get_arc(self, x_start, y, y_curve, x_end): """Render individual arc. x_start (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. y_curve (int): Y-corrdinate of Cubic Bézier y_curve point. x_end (int): X-coordinate of arrow end point....
[ "Render", "individual", "arc", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L158-L170
[ "def", "get_arc", "(", "self", ",", "x_start", ",", "y", ",", "y_curve", ",", "x_end", ")", ":", "template", "=", "\"M{x},{y} C{x},{c} {e},{c} {e},{y}\"", "if", "self", ".", "compact", ":", "template", "=", "\"M{x},{y} {x},{c} {e},{c} {e},{y}\"", "return", "templa...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.get_arrowhead
Render individual arrow head. direction (unicode): Arrow direction, 'left' or 'right'. x (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. end (int): X-coordinate of arrow end point. RETURNS (unicode): Definition of the arrow head path...
spacy/displacy/render.py
def get_arrowhead(self, direction, x, y, end): """Render individual arrow head. direction (unicode): Arrow direction, 'left' or 'right'. x (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. end (int): X-coordinate of arrow end point. ...
def get_arrowhead(self, direction, x, y, end): """Render individual arrow head. direction (unicode): Arrow direction, 'left' or 'right'. x (int): X-coordinate of arrow start point. y (int): Y-coordinate of arrow start and end point. end (int): X-coordinate of arrow end point. ...
[ "Render", "individual", "arrow", "head", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L172-L197
[ "def", "get_arrowhead", "(", "self", ",", "direction", ",", "x", ",", "y", ",", "end", ")", ":", "if", "direction", "==", "\"left\"", ":", "pos1", ",", "pos2", ",", "pos3", "=", "(", "x", ",", "x", "-", "self", ".", "arrow_width", "+", "2", ",", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
DependencyRenderer.get_levels
Calculate available arc height "levels". Used to calculate arrow heights dynamically and without wasting space. args (list): Individual arcs and their start, end, direction and label. RETURNS (list): Arc levels sorted from lowest to highest.
spacy/displacy/render.py
def get_levels(self, arcs): """Calculate available arc height "levels". Used to calculate arrow heights dynamically and without wasting space. args (list): Individual arcs and their start, end, direction and label. RETURNS (list): Arc levels sorted from lowest to highest. """ ...
def get_levels(self, arcs): """Calculate available arc height "levels". Used to calculate arrow heights dynamically and without wasting space. args (list): Individual arcs and their start, end, direction and label. RETURNS (list): Arc levels sorted from lowest to highest. """ ...
[ "Calculate", "available", "arc", "height", "levels", ".", "Used", "to", "calculate", "arrow", "heights", "dynamically", "and", "without", "wasting", "space", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L199-L207
[ "def", "get_levels", "(", "self", ",", "arcs", ")", ":", "levels", "=", "set", "(", "map", "(", "lambda", "arc", ":", "arc", "[", "\"end\"", "]", "-", "arc", "[", "\"start\"", "]", ",", "arcs", ")", ")", "return", "sorted", "(", "list", "(", "lev...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRenderer.render
Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered HTML markup.
spacy/displacy/render.py
def render(self, parsed, page=False, minify=False): """Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered HTML markup. """ render...
def render(self, parsed, page=False, minify=False): """Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped as full HTML page. minify (bool): Minify HTML markup. RETURNS (unicode): Rendered HTML markup. """ render...
[ "Render", "complete", "markup", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L247-L269
[ "def", "render", "(", "self", ",", "parsed", ",", "page", "=", "False", ",", "minify", "=", "False", ")", ":", "rendered", "=", "[", "]", "for", "i", ",", "p", "in", "enumerate", "(", "parsed", ")", ":", "if", "i", "==", "0", ":", "settings", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
EntityRenderer.render_ents
Render entities in text. text (unicode): Original text. spans (list): Individual entity spans and their start, end and label. title (unicode or None): Document title set in Doc.user_data['title'].
spacy/displacy/render.py
def render_ents(self, text, spans, title): """Render entities in text. text (unicode): Original text. spans (list): Individual entity spans and their start, end and label. title (unicode or None): Document title set in Doc.user_data['title']. """ markup = "" offs...
def render_ents(self, text, spans, title): """Render entities in text. text (unicode): Original text. spans (list): Individual entity spans and their start, end and label. title (unicode or None): Document title set in Doc.user_data['title']. """ markup = "" offs...
[ "Render", "entities", "in", "text", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L271-L304
[ "def", "render_ents", "(", "self", ",", "text", ",", "spans", ",", "title", ")", ":", "markup", "=", "\"\"", "offset", "=", "0", "for", "span", "in", "spans", ":", "label", "=", "span", "[", "\"label\"", "]", "start", "=", "span", "[", "\"start\"", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
merge_noun_chunks
Merge noun chunks into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged noun chunks. DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks
spacy/pipeline/functions.py
def merge_noun_chunks(doc): """Merge noun chunks into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged noun chunks. DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks """ if not doc.is_parsed: return doc with doc.retokenize() as reto...
def merge_noun_chunks(doc): """Merge noun chunks into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged noun chunks. DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks """ if not doc.is_parsed: return doc with doc.retokenize() as reto...
[ "Merge", "noun", "chunks", "into", "a", "single", "token", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/functions.py#L7-L21
[ "def", "merge_noun_chunks", "(", "doc", ")", ":", "if", "not", "doc", ".", "is_parsed", ":", "return", "doc", "with", "doc", ".", "retokenize", "(", ")", "as", "retokenizer", ":", "for", "np", "in", "doc", ".", "noun_chunks", ":", "attrs", "=", "{", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
merge_entities
Merge entities into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged entities. DOCS: https://spacy.io/api/pipeline-functions#merge_entities
spacy/pipeline/functions.py
def merge_entities(doc): """Merge entities into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged entities. DOCS: https://spacy.io/api/pipeline-functions#merge_entities """ with doc.retokenize() as retokenizer: for ent in doc.ents: attrs =...
def merge_entities(doc): """Merge entities into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged entities. DOCS: https://spacy.io/api/pipeline-functions#merge_entities """ with doc.retokenize() as retokenizer: for ent in doc.ents: attrs =...
[ "Merge", "entities", "into", "a", "single", "token", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/functions.py#L24-L36
[ "def", "merge_entities", "(", "doc", ")", ":", "with", "doc", ".", "retokenize", "(", ")", "as", "retokenizer", ":", "for", "ent", "in", "doc", ".", "ents", ":", "attrs", "=", "{", "\"tag\"", ":", "ent", ".", "root", ".", "tag", ",", "\"dep\"", ":"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
merge_subtokens
Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens
spacy/pipeline/functions.py
def merge_subtokens(doc, label="subtok"): """Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens """ merger = Match...
def merge_subtokens(doc, label="subtok"): """Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens """ merger = Match...
[ "Merge", "subtokens", "into", "a", "single", "token", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/functions.py#L39-L55
[ "def", "merge_subtokens", "(", "doc", ",", "label", "=", "\"subtok\"", ")", ":", "merger", "=", "Matcher", "(", "doc", ".", "vocab", ")", "merger", ".", "add", "(", "\"SUBTOK\"", ",", "None", ",", "[", "{", "\"DEP\"", ":", "label", ",", "\"op\"", ":"...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
train
Train or update a spaCy model. Requires data to be formatted in spaCy's JSON format. To convert data from other formats, use the `spacy convert` command.
spacy/cli/train.py
def train( lang, output_path, train_path, dev_path, raw_text=None, base_model=None, pipeline="tagger,parser,ner", vectors=None, n_iter=30, n_early_stopping=None, n_examples=0, use_gpu=-1, version="0.0.0", meta_path=None, init_tok2vec=None, parser_multitask...
def train( lang, output_path, train_path, dev_path, raw_text=None, base_model=None, pipeline="tagger,parser,ner", vectors=None, n_iter=30, n_early_stopping=None, n_examples=0, use_gpu=-1, version="0.0.0", meta_path=None, init_tok2vec=None, parser_multitask...
[ "Train", "or", "update", "a", "spaCy", "model", ".", "Requires", "data", "to", "be", "formatted", "in", "spaCy", "s", "JSON", "format", ".", "To", "convert", "data", "from", "other", "formats", "use", "the", "spacy", "convert", "command", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/train.py#L73-L368
[ "def", "train", "(", "lang", ",", "output_path", ",", "train_path", ",", "dev_path", ",", "raw_text", "=", "None", ",", "base_model", "=", "None", ",", "pipeline", "=", "\"tagger,parser,ner\"", ",", "vectors", "=", "None", ",", "n_iter", "=", "30", ",", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
_score_for_model
Returns mean score between tasks in pipeline that can be used for early stopping.
spacy/cli/train.py
def _score_for_model(meta): """ Returns mean score between tasks in pipeline that can be used for early stopping. """ mean_acc = list() pipes = meta["pipeline"] acc = meta["accuracy"] if "tagger" in pipes: mean_acc.append(acc["tags_acc"]) if "parser" in pipes: mean_acc.append((ac...
def _score_for_model(meta): """ Returns mean score between tasks in pipeline that can be used for early stopping. """ mean_acc = list() pipes = meta["pipeline"] acc = meta["accuracy"] if "tagger" in pipes: mean_acc.append(acc["tags_acc"]) if "parser" in pipes: mean_acc.append((ac...
[ "Returns", "mean", "score", "between", "tasks", "in", "pipeline", "that", "can", "be", "used", "for", "early", "stopping", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/train.py#L371-L382
[ "def", "_score_for_model", "(", "meta", ")", ":", "mean_acc", "=", "list", "(", ")", "pipes", "=", "meta", "[", "\"pipeline\"", "]", "acc", "=", "meta", "[", "\"accuracy\"", "]", "if", "\"tagger\"", "in", "pipes", ":", "mean_acc", ".", "append", "(", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
_load_pretrained_tok2vec
Load pre-trained weights for the 'token-to-vector' part of the component models, which is typically a CNN. See 'spacy pretrain'. Experimental.
spacy/cli/train.py
def _load_pretrained_tok2vec(nlp, loc): """Load pre-trained weights for the 'token-to-vector' part of the component models, which is typically a CNN. See 'spacy pretrain'. Experimental. """ with loc.open("rb") as file_: weights_data = file_.read() loaded = [] for name, component in nlp.p...
def _load_pretrained_tok2vec(nlp, loc): """Load pre-trained weights for the 'token-to-vector' part of the component models, which is typically a CNN. See 'spacy pretrain'. Experimental. """ with loc.open("rb") as file_: weights_data = file_.read() loaded = [] for name, component in nlp.p...
[ "Load", "pre", "-", "trained", "weights", "for", "the", "token", "-", "to", "-", "vector", "part", "of", "the", "component", "models", "which", "is", "typically", "a", "CNN", ".", "See", "spacy", "pretrain", ".", "Experimental", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/train.py#L407-L418
[ "def", "_load_pretrained_tok2vec", "(", "nlp", ",", "loc", ")", ":", "with", "loc", ".", "open", "(", "\"rb\"", ")", "as", "file_", ":", "weights_data", "=", "file_", ".", "read", "(", ")", "loaded", "=", "[", "]", "for", "name", ",", "component", "i...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
conllu2json
Convert conllu files into JSON format for use with train cli. use_morphology parameter enables appending morphology to tags, which is useful for languages such as Spanish, where UD tags are not so rich. Extract NER tags if available and convert them so that they follow BILUO and the Wikipedia scheme
spacy/cli/converters/conllu2json.py
def conllu2json(input_data, n_sents=10, use_morphology=False, lang=None): """ Convert conllu files into JSON format for use with train cli. use_morphology parameter enables appending morphology to tags, which is useful for languages such as Spanish, where UD tags are not so rich. Extract NER tags i...
def conllu2json(input_data, n_sents=10, use_morphology=False, lang=None): """ Convert conllu files into JSON format for use with train cli. use_morphology parameter enables appending morphology to tags, which is useful for languages such as Spanish, where UD tags are not so rich. Extract NER tags i...
[ "Convert", "conllu", "files", "into", "JSON", "format", "for", "use", "with", "train", "cli", ".", "use_morphology", "parameter", "enables", "appending", "morphology", "to", "tags", "which", "is", "useful", "for", "languages", "such", "as", "Spanish", "where", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/conllu2json.py#L9-L37
[ "def", "conllu2json", "(", "input_data", ",", "n_sents", "=", "10", ",", "use_morphology", "=", "False", ",", "lang", "=", "None", ")", ":", "# by @dvsrepo, via #11 explosion/spacy-dev-resources", "# by @katarkor", "docs", "=", "[", "]", "sentences", "=", "[", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
is_ner
Check the 10th column of the first token to determine if the file contains NER tags
spacy/cli/converters/conllu2json.py
def is_ner(tag): """ Check the 10th column of the first token to determine if the file contains NER tags """ tag_match = re.match("([A-Z_]+)-([A-Z_]+)", tag) if tag_match: return True elif tag == "O": return True else: return False
def is_ner(tag): """ Check the 10th column of the first token to determine if the file contains NER tags """ tag_match = re.match("([A-Z_]+)-([A-Z_]+)", tag) if tag_match: return True elif tag == "O": return True else: return False
[ "Check", "the", "10th", "column", "of", "the", "first", "token", "to", "determine", "if", "the", "file", "contains", "NER", "tags" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/conllu2json.py#L40-L51
[ "def", "is_ner", "(", "tag", ")", ":", "tag_match", "=", "re", ".", "match", "(", "\"([A-Z_]+)-([A-Z_]+)\"", ",", "tag", ")", "if", "tag_match", ":", "return", "True", "elif", "tag", "==", "\"O\"", ":", "return", "True", "else", ":", "return", "False" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
simplify_tags
Simplify tags obtained from the dataset in order to follow Wikipedia scheme (PER, LOC, ORG, MISC). 'PER', 'LOC' and 'ORG' keep their tags, while 'GPE_LOC' is simplified to 'LOC', 'GPE_ORG' to 'ORG' and all remaining tags to 'MISC'.
spacy/cli/converters/conllu2json.py
def simplify_tags(iob): """ Simplify tags obtained from the dataset in order to follow Wikipedia scheme (PER, LOC, ORG, MISC). 'PER', 'LOC' and 'ORG' keep their tags, while 'GPE_LOC' is simplified to 'LOC', 'GPE_ORG' to 'ORG' and all remaining tags to 'MISC'. """ new_iob = [] for tag in ...
def simplify_tags(iob): """ Simplify tags obtained from the dataset in order to follow Wikipedia scheme (PER, LOC, ORG, MISC). 'PER', 'LOC' and 'ORG' keep their tags, while 'GPE_LOC' is simplified to 'LOC', 'GPE_ORG' to 'ORG' and all remaining tags to 'MISC'. """ new_iob = [] for tag in ...
[ "Simplify", "tags", "obtained", "from", "the", "dataset", "in", "order", "to", "follow", "Wikipedia", "scheme", "(", "PER", "LOC", "ORG", "MISC", ")", ".", "PER", "LOC", "and", "ORG", "keep", "their", "tags", "while", "GPE_LOC", "is", "simplified", "to", ...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/conllu2json.py#L86-L107
[ "def", "simplify_tags", "(", "iob", ")", ":", "new_iob", "=", "[", "]", "for", "tag", "in", "iob", ":", "tag_match", "=", "re", ".", "match", "(", "\"([A-Z_]+)-([A-Z_]+)\"", ",", "tag", ")", "if", "tag_match", ":", "prefix", "=", "tag_match", ".", "gro...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
info
Print info about spaCy installation. If a model shortcut link is speficied as an argument, print model information. Flag --markdown prints details in Markdown for easy copy-pasting to GitHub issues.
spacy/cli/info.py
def info(model=None, markdown=False, silent=False): """ Print info about spaCy installation. If a model shortcut link is speficied as an argument, print model information. Flag --markdown prints details in Markdown for easy copy-pasting to GitHub issues. """ msg = Printer() if model: ...
def info(model=None, markdown=False, silent=False): """ Print info about spaCy installation. If a model shortcut link is speficied as an argument, print model information. Flag --markdown prints details in Markdown for easy copy-pasting to GitHub issues. """ msg = Printer() if model: ...
[ "Print", "info", "about", "spaCy", "installation", ".", "If", "a", "model", "shortcut", "link", "is", "speficied", "as", "an", "argument", "print", "model", "information", ".", "Flag", "--", "markdown", "prints", "details", "in", "Markdown", "for", "easy", "...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/info.py#L20-L64
[ "def", "info", "(", "model", "=", "None", ",", "markdown", "=", "False", ",", "silent", "=", "False", ")", ":", "msg", "=", "Printer", "(", ")", "if", "model", ":", "if", "util", ".", "is_package", "(", "model", ")", ":", "model_path", "=", "util",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
print_markdown
Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2.
spacy/cli/info.py
def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ markdown = [] for key, value in data.items(): if isinstance(value...
def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ markdown = [] for key, value in data.items(): if isinstance(value...
[ "Print", "data", "in", "GitHub", "-", "flavoured", "Markdown", "format", "for", "issues", "etc", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/info.py#L80-L93
[ "def", "print_markdown", "(", "data", ",", "title", "=", "None", ")", ":", "markdown", "=", "[", "]", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "basestring_", ")", "and", "Path", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
main
Load the model, set up the pipeline and train the parser.
examples/training/train_intent_parser.py
def main(model=None, output_dir=None, n_iter=15): """Load the model, set up the pipeline and train the parser.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank Language class...
def main(model=None, output_dir=None, n_iter=15): """Load the model, set up the pipeline and train the parser.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank Language class...
[ "Load", "the", "model", "set", "up", "the", "pipeline", "and", "train", "the", "parser", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_intent_parser.py#L107-L154
[ "def", "main", "(", "model", "=", "None", ",", "output_dir", "=", "None", ",", "n_iter", "=", "15", ")", ":", "if", "model", "is", "not", "None", ":", "nlp", "=", "spacy", ".", "load", "(", "model", ")", "# load existing spaCy model", "print", "(", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.get_pipe
Get a pipeline component for a given component name. name (unicode): Name of pipeline component to get. RETURNS (callable): The pipeline component. DOCS: https://spacy.io/api/language#get_pipe
spacy/language.py
def get_pipe(self, name): """Get a pipeline component for a given component name. name (unicode): Name of pipeline component to get. RETURNS (callable): The pipeline component. DOCS: https://spacy.io/api/language#get_pipe """ for pipe_name, component in self.pipeline: ...
def get_pipe(self, name): """Get a pipeline component for a given component name. name (unicode): Name of pipeline component to get. RETURNS (callable): The pipeline component. DOCS: https://spacy.io/api/language#get_pipe """ for pipe_name, component in self.pipeline: ...
[ "Get", "a", "pipeline", "component", "for", "a", "given", "component", "name", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L232-L243
[ "def", "get_pipe", "(", "self", ",", "name", ")", ":", "for", "pipe_name", ",", "component", "in", "self", ".", "pipeline", ":", "if", "pipe_name", "==", "name", ":", "return", "component", "raise", "KeyError", "(", "Errors", ".", "E001", ".", "format", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.create_pipe
Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component. DOCS: https://spacy.io/api/language#create_pipe
spacy/language.py
def create_pipe(self, name, config=dict()): """Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component. DOCS: https://spa...
def create_pipe(self, name, config=dict()): """Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component. DOCS: https://spa...
[ "Create", "a", "pipeline", "component", "from", "a", "factory", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L245-L260
[ "def", "create_pipe", "(", "self", ",", "name", ",", "config", "=", "dict", "(", ")", ")", ":", "if", "name", "not", "in", "self", ".", "factories", ":", "if", "name", "==", "\"sbd\"", ":", "raise", "KeyError", "(", "Errors", ".", "E108", ".", "for...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.add_pipe
Add a component to the processing pipeline. Valid components are callables that take a `Doc` object, modify it and return it. Only one of before/after/first/last can be set. Default behaviour is "last". component (callable): The pipeline component. name (unicode): Name of pipeline compo...
spacy/language.py
def add_pipe( self, component, name=None, before=None, after=None, first=None, last=None ): """Add a component to the processing pipeline. Valid components are callables that take a `Doc` object, modify it and return it. Only one of before/after/first/last can be set. Default behavio...
def add_pipe( self, component, name=None, before=None, after=None, first=None, last=None ): """Add a component to the processing pipeline. Valid components are callables that take a `Doc` object, modify it and return it. Only one of before/after/first/last can be set. Default behavio...
[ "Add", "a", "component", "to", "the", "processing", "pipeline", ".", "Valid", "components", "are", "callables", "that", "take", "a", "Doc", "object", "modify", "it", "and", "return", "it", ".", "Only", "one", "of", "before", "/", "after", "/", "first", "...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L262-L313
[ "def", "add_pipe", "(", "self", ",", "component", ",", "name", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ",", "first", "=", "None", ",", "last", "=", "None", ")", ":", "if", "not", "hasattr", "(", "component", ",", "\"__ca...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.replace_pipe
Replace a component in the pipeline. name (unicode): Name of the component to replace. component (callable): Pipeline component. DOCS: https://spacy.io/api/language#replace_pipe
spacy/language.py
def replace_pipe(self, name, component): """Replace a component in the pipeline. name (unicode): Name of the component to replace. component (callable): Pipeline component. DOCS: https://spacy.io/api/language#replace_pipe """ if name not in self.pipe_names: ...
def replace_pipe(self, name, component): """Replace a component in the pipeline. name (unicode): Name of the component to replace. component (callable): Pipeline component. DOCS: https://spacy.io/api/language#replace_pipe """ if name not in self.pipe_names: ...
[ "Replace", "a", "component", "in", "the", "pipeline", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L326-L336
[ "def", "replace_pipe", "(", "self", ",", "name", ",", "component", ")", ":", "if", "name", "not", "in", "self", ".", "pipe_names", ":", "raise", "ValueError", "(", "Errors", ".", "E001", ".", "format", "(", "name", "=", "name", ",", "opts", "=", "sel...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.rename_pipe
Rename a pipeline component. old_name (unicode): Name of the component to rename. new_name (unicode): New name of the component. DOCS: https://spacy.io/api/language#rename_pipe
spacy/language.py
def rename_pipe(self, old_name, new_name): """Rename a pipeline component. old_name (unicode): Name of the component to rename. new_name (unicode): New name of the component. DOCS: https://spacy.io/api/language#rename_pipe """ if old_name not in self.pipe_names: ...
def rename_pipe(self, old_name, new_name): """Rename a pipeline component. old_name (unicode): Name of the component to rename. new_name (unicode): New name of the component. DOCS: https://spacy.io/api/language#rename_pipe """ if old_name not in self.pipe_names: ...
[ "Rename", "a", "pipeline", "component", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L338-L351
[ "def", "rename_pipe", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "if", "old_name", "not", "in", "self", ".", "pipe_names", ":", "raise", "ValueError", "(", "Errors", ".", "E001", ".", "format", "(", "name", "=", "old_name", ",", "opts", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.remove_pipe
Remove a component from the pipeline. name (unicode): Name of the component to remove. RETURNS (tuple): A `(name, component)` tuple of the removed component. DOCS: https://spacy.io/api/language#remove_pipe
spacy/language.py
def remove_pipe(self, name): """Remove a component from the pipeline. name (unicode): Name of the component to remove. RETURNS (tuple): A `(name, component)` tuple of the removed component. DOCS: https://spacy.io/api/language#remove_pipe """ if name not in self.pipe_nam...
def remove_pipe(self, name): """Remove a component from the pipeline. name (unicode): Name of the component to remove. RETURNS (tuple): A `(name, component)` tuple of the removed component. DOCS: https://spacy.io/api/language#remove_pipe """ if name not in self.pipe_nam...
[ "Remove", "a", "component", "from", "the", "pipeline", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L353-L363
[ "def", "remove_pipe", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "pipe_names", ":", "raise", "ValueError", "(", "Errors", ".", "E001", ".", "format", "(", "name", "=", "name", ",", "opts", "=", "self", ".", "pipe_name...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.update
Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. RETURNS (dict): Results from the update. DOCS: https://spacy.io/api/language#upda...
spacy/language.py
def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None): """Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. ...
def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None): """Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. ...
[ "Update", "the", "models", "in", "the", "pipeline", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L408-L459
[ "def", "update", "(", "self", ",", "docs", ",", "golds", ",", "drop", "=", "0.0", ",", "sgd", "=", "None", ",", "losses", "=", "None", ",", "component_cfg", "=", "None", ")", ":", "if", "len", "(", "docs", ")", "!=", "len", "(", "golds", ")", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.rehearse
Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial ones. This is useful for keeping a pre-trained model on-track, even...
spacy/language.py
def rehearse(self, docs, sgd=None, losses=None, config=None): """Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial on...
def rehearse(self, docs, sgd=None, losses=None, config=None): """Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial on...
[ "Make", "a", "rehearsal", "update", "to", "the", "models", "in", "the", "pipeline", "to", "prevent", "forgetting", ".", "Rehearsal", "updates", "run", "an", "initial", "copy", "of", "the", "model", "over", "some", "data", "and", "update", "the", "model", "...
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L461-L511
[ "def", "rehearse", "(", "self", ",", "docs", ",", "sgd", "=", "None", ",", "losses", "=", "None", ",", "config", "=", "None", ")", ":", "# TODO: document", "if", "len", "(", "docs", ")", "==", "0", ":", "return", "if", "sgd", "is", "None", ":", "...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.preprocess_gold
Can be called before training to pre-process gold data. By default, it handles nonprojectivity and adds missing tags to the tag map. docs_golds (iterable): Tuples of `Doc` and `GoldParse` objects. YIELDS (tuple): Tuples of preprocessed `Doc` and `GoldParse` objects.
spacy/language.py
def preprocess_gold(self, docs_golds): """Can be called before training to pre-process gold data. By default, it handles nonprojectivity and adds missing tags to the tag map. docs_golds (iterable): Tuples of `Doc` and `GoldParse` objects. YIELDS (tuple): Tuples of preprocessed `Doc` and...
def preprocess_gold(self, docs_golds): """Can be called before training to pre-process gold data. By default, it handles nonprojectivity and adds missing tags to the tag map. docs_golds (iterable): Tuples of `Doc` and `GoldParse` objects. YIELDS (tuple): Tuples of preprocessed `Doc` and...
[ "Can", "be", "called", "before", "training", "to", "pre", "-", "process", "gold", "data", ".", "By", "default", "it", "handles", "nonprojectivity", "and", "adds", "missing", "tags", "to", "the", "tag", "map", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L513-L524
[ "def", "preprocess_gold", "(", "self", ",", "docs_golds", ")", ":", "for", "name", ",", "proc", "in", "self", ".", "pipeline", ":", "if", "hasattr", "(", "proc", ",", "\"preprocess_gold\"", ")", ":", "docs_golds", "=", "proc", ".", "preprocess_gold", "(", ...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.begin_training
Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config parameters for specific components. **cfg: Config parameters. RETURNS: An optimizer. ...
spacy/language.py
def begin_training(self, get_gold_tuples=None, sgd=None, component_cfg=None, **cfg): """Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config paramet...
def begin_training(self, get_gold_tuples=None, sgd=None, component_cfg=None, **cfg): """Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config paramet...
[ "Allocate", "models", "pre", "-", "process", "training", "data", "and", "acquire", "a", "trainer", "and", "optimizer", ".", "Used", "as", "a", "contextmanager", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L526-L567
[ "def", "begin_training", "(", "self", ",", "get_gold_tuples", "=", "None", ",", "sgd", "=", "None", ",", "component_cfg", "=", "None", ",", "*", "*", "cfg", ")", ":", "if", "get_gold_tuples", "is", "None", ":", "get_gold_tuples", "=", "lambda", ":", "[",...
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
Language.resume_training
Continue training a pre-trained model. Create and return an optimizer, and initialize "rehearsal" for any pipeline component that has a .rehearse() method. Rehearsal is used to prevent models from "forgetting" their initialised "knowledge". To perform rehearsal, collect samples of text ...
spacy/language.py
def resume_training(self, sgd=None, **cfg): """Continue training a pre-trained model. Create and return an optimizer, and initialize "rehearsal" for any pipeline component that has a .rehearse() method. Rehearsal is used to prevent models from "forgetting" their initialised "knowledge"....
def resume_training(self, sgd=None, **cfg): """Continue training a pre-trained model. Create and return an optimizer, and initialize "rehearsal" for any pipeline component that has a .rehearse() method. Rehearsal is used to prevent models from "forgetting" their initialised "knowledge"....
[ "Continue", "training", "a", "pre", "-", "trained", "model", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L569-L591
[ "def", "resume_training", "(", "self", ",", "sgd", "=", "None", ",", "*", "*", "cfg", ")", ":", "if", "cfg", ".", "get", "(", "\"device\"", ",", "-", "1", ")", ">=", "0", ":", "util", ".", "use_gpu", "(", "cfg", "[", "\"device\"", "]", ")", "if...
8ee4100f8ffb336886208a1ea827bf4c745e2709