mirror of
				https://github.com/explosion/spaCy.git
				synced 2025-10-31 16:07:41 +03:00 
			
		
		
		
	* Update with WIP * Update with WIP * Update with pipeline serialization * Update types and pipe factories * Add deep merge, tidy up and add tests * Fix pipe creation from config * Don't validate default configs on load * Update spacy/language.py Co-authored-by: Ines Montani <ines@ines.io> * Adjust factory/component meta error * Clean up factory args and remove defaults * Add test for failing empty dict defaults * Update pipeline handling and methods * provide KB as registry function instead of as object * small change in test to make functionality more clear * update example script for EL configuration * Fix typo * Simplify test * Simplify test * splitting pipes.pyx into separate files * moving default configs to each component file * fix batch_size type * removing default values from component constructors where possible (TODO: test 4725) * skip instead of xfail * Add test for config -> nlp with multiple instances * pipeline.pipes -> pipeline.pipe * Tidy up, document, remove kwargs * small cleanup/generalization for Tok2VecListener * use DEFAULT_UPSTREAM field * revert to avoid circular imports * Fix tests * Replace deprecated arg * Make model dirs require config * fix pickling of keyword-only arguments in constructor * WIP: clean up and integrate full config * Add helper to handle function args more reliably Now also includes keyword-only args * Fix config composition and serialization * Improve config debugging and add visual diff * Remove unused defaults and fix type * Remove pipeline and factories from meta * Update spacy/default_config.cfg Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Update spacy/default_config.cfg * small UX edits * avoid printing stack trace for debug CLI commands * Add support for language-specific factories * specify the section of the config which holds the model to debug * WIP: add Language.from_config * Update with language data refactor WIP * Auto-format * Add backwards-compat handling for Language.factories * Update morphologizer.pyx * Fix morphologizer * Update and simplify lemmatizers * Fix Japanese tests * Port over tagger changes * Fix Chinese and tests * Update to latest Thinc * WIP: xfail first Russian lemmatizer test * Fix component-specific overrides * fix nO for output layers in debug_model * Fix default value * Fix tests and don't pass objects in config * Fix deep merging * Fix lemma lookup data registry Only load the lookups if an entry is available in the registry (and if spacy-lookups-data is installed) * Add types * Add Vocab.from_config * Fix typo * Fix tests * Make config copying more elegant * Fix pipe analysis * Fix lemmatizers and is_base_form * WIP: move language defaults to config * Fix morphology type * Fix vocab * Remove comment * Update to latest Thinc * Add morph rules to config * Tidy up * Remove set_morphology option from tagger factory * Hack use_gpu * Move [pipeline] to top-level block and make [nlp.pipeline] list Allows separating component blocks from component order – otherwise, ordering the config would mean a changed component order, which is bad. Also allows initial config to define more components and not use all of them * Fix use_gpu and resume in CLI * Auto-format * Remove resume from config * Fix formatting and error * [pipeline] -> [components] * Fix types * Fix tagger test: requires set_morphology? Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com> Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
		
			
				
	
	
		
			96 lines
		
	
	
		
			3.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			96 lines
		
	
	
		
			3.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| from thinc.api import concatenate, reduce_max, reduce_mean, siamese, CauchySimilarity
 | |
| 
 | |
| from .pipe import Pipe
 | |
| from ..util import link_vectors_to_models
 | |
| 
 | |
| 
 | |
| # TODO: do we want to keep these?
 | |
| 
 | |
| 
 | |
| class SentenceSegmenter:
 | |
|     """A simple spaCy hook, to allow custom sentence boundary detection logic
 | |
|     (that doesn't require the dependency parse). To change the sentence
 | |
|     boundary detection strategy, pass a generator function `strategy` on
 | |
|     initialization, or assign a new strategy to the .strategy attribute.
 | |
|     Sentence detection strategies should be generators that take `Doc` objects
 | |
|     and yield `Span` objects for each sentence.
 | |
|     """
 | |
| 
 | |
|     def __init__(self, vocab, strategy=None):
 | |
|         self.vocab = vocab
 | |
|         if strategy is None or strategy == "on_punct":
 | |
|             strategy = self.split_on_punct
 | |
|         self.strategy = strategy
 | |
| 
 | |
|     def __call__(self, doc):
 | |
|         doc.user_hooks["sents"] = self.strategy
 | |
|         return doc
 | |
| 
 | |
|     @staticmethod
 | |
|     def split_on_punct(doc):
 | |
|         start = 0
 | |
|         seen_period = False
 | |
|         for i, token in enumerate(doc):
 | |
|             if seen_period and not token.is_punct:
 | |
|                 yield doc[start : token.i]
 | |
|                 start = token.i
 | |
|                 seen_period = False
 | |
|             elif token.text in [".", "!", "?"]:
 | |
|                 seen_period = True
 | |
|         if start < len(doc):
 | |
|             yield doc[start : len(doc)]
 | |
| 
 | |
| 
 | |
| class SimilarityHook(Pipe):
 | |
|     """
 | |
|     Experimental: A pipeline component to install a hook for supervised
 | |
|     similarity into `Doc` objects.
 | |
|     The similarity model can be any object obeying the Thinc `Model`
 | |
|     interface. By default, the model concatenates the elementwise mean and
 | |
|     elementwise max of the two tensors, and compares them using the
 | |
|     Cauchy-like similarity function from Chen (2013):
 | |
| 
 | |
|         >>> similarity = 1. / (1. + (W * (vec1-vec2)**2).sum())
 | |
| 
 | |
|     Where W is a vector of dimension weights, initialized to 1.
 | |
|     """
 | |
| 
 | |
|     def __init__(self, vocab, model=True, **cfg):
 | |
|         self.vocab = vocab
 | |
|         self.model = model
 | |
|         self.cfg = dict(cfg)
 | |
| 
 | |
|     @classmethod
 | |
|     def Model(cls, length):
 | |
|         return siamese(
 | |
|             concatenate(reduce_max(), reduce_mean()), CauchySimilarity(length * 2)
 | |
|         )
 | |
| 
 | |
|     def __call__(self, doc):
 | |
|         """Install similarity hook"""
 | |
|         doc.user_hooks["similarity"] = self.predict
 | |
|         return doc
 | |
| 
 | |
|     def pipe(self, docs, **kwargs):
 | |
|         for doc in docs:
 | |
|             yield self(doc)
 | |
| 
 | |
|     def predict(self, doc1, doc2):
 | |
|         return self.model.predict([(doc1, doc2)])
 | |
| 
 | |
|     def update(self, doc1_doc2, golds, sgd=None, drop=0.0):
 | |
|         sims, bp_sims = self.model.begin_update(doc1_doc2)
 | |
| 
 | |
|     def begin_training(self, _=tuple(), pipeline=None, sgd=None, **kwargs):
 | |
|         """Allocate model, using nO from the first model in the pipeline.
 | |
| 
 | |
|         gold_tuples (iterable): Gold-standard training data.
 | |
|         pipeline (list): The pipeline the model is part of.
 | |
|         """
 | |
|         if self.model is True:
 | |
|             self.model = self.Model(pipeline[0].model.get_dim("nO"))
 | |
|             link_vectors_to_models(self.vocab)
 | |
|         if sgd is None:
 | |
|             sgd = self.create_optimizer()
 | |
|         return sgd
 |