<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 spaCy Tutorial
(C) 2019-2020 by Damir Cavar
Version
Step1:  We can load the English NLP pipeline in the following way
Step2:  Tokenization
Step3:  Part-of-Speech Tagging
We can tokenize and part of speech tag the individual tokens using the following code
Step4:  The above output contains for every token in a line the token itself, the lemma, the Part-of-Speech tag, the dependency label, the orthographic shape (upper and lower case characters as X or x respectively), the boolean for the token being an alphanumeric string, and the boolean for it being a stopword.
Dependency Parse
Using the same approach as above for PoS-tags, we can print the Dependency Parse relations
Step5:  As specified in the code, each line represents one token. The token is printed in the first column, followed by the dependency relation to it from the token in the third column, followed by its main category type.
Named Entity Recognition
Similarly to PoS-tags and Dependency Parse Relations, we can print out Named Entity labels
Step6:  We can extend the input with some more entities
Step7:  The corresponding NE-labels are
Step8:  Pattern Matching in spaCy
Step9:  spaCy is Missing
From the linguistic standpoint, when looking at the analytical output of the NLP pipeline in spaCy, there are some important components missing
Step10:  We can load the visualizer
Step11:  Loading the English NLP pipeline
Step12:  Process an input sentence
Step13:  If you want to generate a visualization running code outside of the Jupyter notebook, you could use the following code. You should not use this code, if you are running the notebook. Instead, use the function display.render two cells below.
Visualizing the Dependency Parse tree can be achieved by running the following server code and opening up a new tab on the URL http
Step14:  Instead of serving the graph, one can render it directly into a Jupyter Notebook
Step16:  In addition to the visualization of the Dependency Trees, we can visualize named entity annotations
Step17:  Vectors
To use vectors in spaCy, you might consider installing the larger models for the particular language. The common module and language packages only come with the small models. The larger models can be installed as described on the spaCy vectors page
Step18:  We can now import the English NLP pipeline to process some word list. Since the small models in spacy only include context-sensitive tensors, we should use the dowloaded large model for better word vectors. We load the large model as follows
Step19:  We can process a list of words by the pipeline using the nlp object
Step20:  As described in the spaCy chapter Word Vectors and Semantic Similarity, the resulting elements of Doc, Span, and Token provide a method similarity(), which returns the similarities between words
Step21:  We can access the vectors of these objects using the vector attribute
Step22:  The attribute has_vector returns a boolean depending on whether the token has a vector in the model or not. The token sasquatch has no vector. It is also out-of-vocabulary (OOV), as the fourth column shows. Thus, it also has a norm of $0$, that is, it has a length of $0$.
Here the token vector has a length of $300$. We can print out the vector for a token
Step23:  Here just another example of similarities for some famous words
Step24:  Similarities in Context
In spaCy parsing, tagging and NER models make use of vector representations of contexts that represent the meaning of words. A text meaning representation is represented as an array of floats, i.e. a tensor, computed during the NLP pipeline processing. With this approach words that have not been seen before can be typed or classified. SpaCy uses a 4-layer convolutional network for the computation of these tensors. In this approach these tensors model a context of four words left and right of any given word.
Let us use the example from the spaCy documentation and check the word labrador
Step25:  We can now test for the context
Step26:  Using this strategy we can compute document or text similarities as well
Step27:  We can vary the word order in sentences and compare them
Step28:  Custom Models
Optimization
Step29:  Training Models
This example code for training an NER model is based on the training example in spaCy.
We will import some components from the future module. Read its documentation here.
Step30:  We import the random module for pseudo-random number generation
Step31:  We import the Path object from the pathlib module
Step32:  We import spaCy
Step33:  We also import the minibatch and compounding module from spaCy.utils
Step34:  The training data is formated as JSON
Step35:  We created a blank 'xx' model
Step36:  We add the named entity labels to the NER model
Step37:  Assuming that the model is empty and untrained, we reset and initialize the weights randomly using
Step38:  We would not do this, if the model is supposed to be tuned or retrained on new data.
We get all pipe-names in the model that are not our NER related pipes to disable them during training
Step39:  We can now disable the other pipes and train just the NER uing 100 iterations
Step40:  We can test the trained model
Step41:  We can define the output directory where the model will be saved as the models folder in the directory where the notebook is running
Step42:  Save model to output dir
Step43:  To make sure everything worked out well, we can test the saved model
<ASSISTANT_TASK:>
Python Code:
import spacy
Explanation: spaCy Tutorial
(C) 2019-2020 by Damir Cavar
Version: 1.4, February 2020
Download: This and various other Jupyter notebooks are available from my GitHub repo.
This is a tutorial related to the L665 course on Machine Learning for NLP focusing on Deep Learning, Spring 2018 at Indiana University. The following tutorial assumes that you are using a newer distribution of Python 3 and spaCy 2.2 or newer.
Introduction to spaCy
Follow the instructions on the spaCy homepage about installation of the module and language models. Your local spaCy module is correctly installed, if the following command is successfull:
End of explanation
nlp = spacy.load("en_core_web_sm")
Explanation: We can load the English NLP pipeline in the following way:
End of explanation
doc = nlp(u'Human ambition is the key to staying ahead of automation.')
for token in doc:
    print(token.text)
Explanation: Tokenization
End of explanation
doc = nlp(u'John bought a car and Mary a motorcycle.')
for token in doc:
    print("\t".join( (token.text, str(token.idx), token.lemma_, token.pos_, token.tag_, token.dep_,
          token.shape_, str(token.is_alpha), str(token.is_stop) )))
Explanation: Part-of-Speech Tagging
We can tokenize and part of speech tag the individual tokens using the following code:
End of explanation
for token in doc:
    print(token.text, token.dep_, token.head.text, token.head.pos_,
          [child for child in token.children])
Explanation: The above output contains for every token in a line the token itself, the lemma, the Part-of-Speech tag, the dependency label, the orthographic shape (upper and lower case characters as X or x respectively), the boolean for the token being an alphanumeric string, and the boolean for it being a stopword.
Dependency Parse
Using the same approach as above for PoS-tags, we can print the Dependency Parse relations:
End of explanation
for ent in doc.ents:
    print(ent.text, ent.start_char, ent.end_char, ent.label_)
Explanation: As specified in the code, each line represents one token. The token is printed in the first column, followed by the dependency relation to it from the token in the third column, followed by its main category type.
Named Entity Recognition
Similarly to PoS-tags and Dependency Parse Relations, we can print out Named Entity labels:
End of explanation
doc = nlp(u'Ali Hassan Kuban said that Apple Inc. will buy Google in May 2018.')
Explanation: We can extend the input with some more entities:
End of explanation
for ent in doc.ents:
    print(ent.text, ent.start_char, ent.end_char, ent.label_)
Explanation: The corresponding NE-labels are:
End of explanation
from spacy.matcher import Matcher
matcher = Matcher(nlp.vocab)
pattern = [{'LOWER': 'hello'}, {'IS_PUNCT': True}, {'LOWER': 'world'}]
matcher.add('HelloWorld', None, pattern)
doc = nlp(u'Hello, world! Hello... world!')
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print(match_id, string_id, start, end, span.text)
print("-" * 50)
doc = nlp(u'Hello, world! Hello world!')
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print(match_id, string_id, start, end, span.text)
Explanation: Pattern Matching in spaCy
End of explanation
import spacy
Explanation: spaCy is Missing
From the linguistic standpoint, when looking at the analytical output of the NLP pipeline in spaCy, there are some important components missing:
Clause boundary detection
Constituent structure trees (scope relations over constituents and phrases)
Anaphora resolution
Coreference analysis
Temporal reference resolution
...
Clause Boundary Detection
Complex sentences consist of clauses. For precise processing of semantic properties of natural language utterances we need to segment the sentences into clauses. The following sentence:
The man said that the woman claimed that the child broke the toy.
can be broken into the following clauses:
Matrix clause: [ the man said ]
Embedded clause: [ that the woman claimed ]
Embedded clause: [ that the child broke the toy ]
These clauses do not form an ordered list or flat sequence, they in fact are hierarchically organized. The matrix clause verb selects as its complement an embedded finite clause with the complementizer that. The embedded predicate claimed selects the same kind of clausal complement. We express this hierarchical relation in form of embedding in tree representations:
[ the man said [ that the woman claimed [ that the child broke the toy ] ] ]
Or using a graphical representation in form of a tree:
<img src="Embedded_Clauses_1.png" width="60%" height="60%">
The hierarchical relation of sub-clauses is relevant when it comes to semantics. The clause John sold his car can be interpreted as an assertion that describes an event with John as the agent, and the car as the object of a selling event in the past. If the clause is embedded under a matrix clause that contains a sentential negation, the proposition is assumed to NOT be true: [ Mary did not say that [ John sold his car ] ] 
It is possible with additional effort to translate the Dependency Trees into clauses and reconstruct the clause hierarchy into a relevant form or data structure. SpaCy does not offer a direct data output of such relations.
One problem still remains, and this is clausal discontinuities. None of the common NLP pipelines, and spaCy in particular, can deal with any kind of discontinuities in any reasonable way. Discontinuities can be observed when sytanctic structures are split over the clause or sentence, or elements ocur in a cannoically different position, as in the following example:
Which car did John claim that Mary took?
The embedded clause consists of the sequence [ Mary took which car ]. One part of the sequence appears dislocated and precedes the matrix clause in the above example. Simple Dependency Parsers cannot generate any reasonable output that makes it easy to identify and reconstruct the relations of clausal elements in these structures.
Constitutent Structure Trees
Dependency Parse trees are a simplification of relations of elements in the clause. They ignore structural and hierarchical relations in a sentence or clause, as shown in the examples above. Instead the Dependency Parse trees show simple functional relations in the sense of sentential functions like subject or object of a verb.
SpaCy does not output any kind of constituent structure and more detailed relational properties of phrases and more complex structural units in a sentence or clause.
Since many semantic properties are defined or determined in terms of structural relations and hierarchies, that is scope relations, this is more complicated to reconstruct or map from the Dependency Parse trees.
Anaphora Resolution
SpaCy does not offer any anaphora resolution annotation. That is, the referent of a pronoun, as in the following examples, is not annotated in the resulting linguistic data structure:
John saw him.
John said that he saw the house.
Tim sold his house. He moved to Paris.
John saw himself in the mirror.
Knowing the restrictions of pronominal binding (in English for example), we can partially generate the potential or most likely anaphora - antecedent relations. This - however - is not part of the spaCy output.
One problem, however, is that spaCy does not provide parse trees of the constituent structure and clausal hierarchies, which is crucial for the correct analysis of pronominal anaphoric relations.
Coreference Analysis
Some NLP pipelines are capable of providing coreference analyses for constituents in clauses. For example, the two clauses should be analyzed as talking about the same subject:
The CEO of Apple, Tim Cook, decided to apply for a job at Google. Cook said that he is not satisfied with the quality of the iPhones anymore. He prefers the Pixel 2.
The constituents [ the CEO of Apple, Tim Cook ] in the first sentence, [ Cook ] in the second sentence, and [ he ] in the third, should all be tagged as referencing the same entity, that is the one mentioned in the first sentence. SpaCy does not provide such a level of analysis or annotation.
Temporal Reference
For various analysis levels it is essential to identify the time references in a sentence or utterance, for example the time the utterance is made or the time the described event happened.
Certain tenses are expressed as periphrastic constructions, including auxiliaries and main verbs. SpaCy does not provide the relevant information to identify these constructions and tenses.
Using the Dependency Parse Visualizer
More on Dependency Parse trees
End of explanation
from spacy import displacy
Explanation: We can load the visualizer:
End of explanation
nlp = spacy.load("en_core_web_sm")
Explanation: Loading the English NLP pipeline:
End of explanation
#doc = nlp(u'John said yesterday that Mary bought a new car for her older son.')
#doc = nlp(u"Dick ran and Jane danced yesterday.")
#doc = nlp(u"Tim Cook is the CEO of Apple.")
#doc = nlp(u"Born in a small town, she took the midnight train going anywhere.")
doc = nlp(u"John met Peter and Susan called Paul.")
Explanation: Process an input sentence:
End of explanation
displacy.serve(doc, style='dep')
Explanation: If you want to generate a visualization running code outside of the Jupyter notebook, you could use the following code. You should not use this code, if you are running the notebook. Instead, use the function display.render two cells below.
Visualizing the Dependency Parse tree can be achieved by running the following server code and opening up a new tab on the URL http://localhost:5000/. You can shut down the server by clicking on the stop button at the top in the notebook toolbar.
End of explanation
displacy.render(doc, style='dep', jupyter=True, options={"distance": 120})
Explanation: Instead of serving the graph, one can render it directly into a Jupyter Notebook:
End of explanation
text = Apple decided to fire Tim Cook and hire somebody called John Doe as the new CEO.
They also discussed a merger with Google. On the long run it seems more likely that Apple
will merge with Amazon and Microsoft with Google. The companies will all relocate to
Austin in Texas before the end of the century. John Doe bought a Prosche.
doc = nlp(text)
displacy.render(doc, style='ent', jupyter=True)
Explanation: In addition to the visualization of the Dependency Trees, we can visualize named entity annotations:
End of explanation
import spacy
Explanation: Vectors
To use vectors in spaCy, you might consider installing the larger models for the particular language. The common module and language packages only come with the small models. The larger models can be installed as described on the spaCy vectors page:
python -m spacy download en_core_web_lg
The large model en_core_web_lg contains more than 1 million unique vectors.
Let us restart all necessary modules again, in particular spaCy:
End of explanation
nlp = spacy.load('en_core_web_lg')
#nlp = spacy.load("en_core_web_sm")
Explanation: We can now import the English NLP pipeline to process some word list. Since the small models in spacy only include context-sensitive tensors, we should use the dowloaded large model for better word vectors. We load the large model as follows:
End of explanation
tokens = nlp(u'dog poodle beagle cat banana apple')
Explanation: We can process a list of words by the pipeline using the nlp object:
End of explanation
for token1 in tokens:
    for token2 in tokens:
        print(token1, token2, token1.similarity(token2))
Explanation: As described in the spaCy chapter Word Vectors and Semantic Similarity, the resulting elements of Doc, Span, and Token provide a method similarity(), which returns the similarities between words:
End of explanation
tokens = nlp(u'dog cat banana sasquatch')
for token in tokens:
    print(token.text, token.has_vector, token.vector_norm, token.is_oov)
Explanation: We can access the vectors of these objects using the vector attribute:
End of explanation
n = 0
print(tokens[n].text, len(tokens[n].vector), tokens[n].vector)
Explanation: The attribute has_vector returns a boolean depending on whether the token has a vector in the model or not. The token sasquatch has no vector. It is also out-of-vocabulary (OOV), as the fourth column shows. Thus, it also has a norm of $0$, that is, it has a length of $0$.
Here the token vector has a length of $300$. We can print out the vector for a token:
End of explanation
tokens = nlp(u'queen king chef')
for token1 in tokens:
    for token2 in tokens:
        print(token1, token2, token1.similarity(token2))
Explanation: Here just another example of similarities for some famous words:
End of explanation
tokens = nlp(u'labrador')
for token in tokens:
    print(token.text, token.has_vector, token.vector_norm, token.is_oov)
Explanation: Similarities in Context
In spaCy parsing, tagging and NER models make use of vector representations of contexts that represent the meaning of words. A text meaning representation is represented as an array of floats, i.e. a tensor, computed during the NLP pipeline processing. With this approach words that have not been seen before can be typed or classified. SpaCy uses a 4-layer convolutional network for the computation of these tensors. In this approach these tensors model a context of four words left and right of any given word.
Let us use the example from the spaCy documentation and check the word labrador:
End of explanation
doc1 = nlp(u"The labrador barked.")
doc2 = nlp(u"The labrador swam.")
doc3 = nlp(u"the labrador people live in canada.")
dog = nlp(u"dog")
count = 0
for doc in [doc1, doc2, doc3]:
    lab = doc[1]
    count += 1
    print(str(count) + ":", lab.similarity(dog))
Explanation: We can now test for the context:
End of explanation
docs = ( nlp(u"Paris is the largest city in France."),
        nlp(u"Vilnius is the capital of Lithuania."),
        nlp(u"An emu is a large bird.") )
for x in range(len(docs)):
    for y in range(len(docs)):
        print(x, y, docs[x].similarity(docs[y]))
Explanation: Using this strategy we can compute document or text similarities as well:
End of explanation
docs = [nlp(u"dog bites man"), nlp(u"man bites dog"),
        nlp(u"man dog bites"), nlp(u"cat eats mouse")]
for doc in docs:
    for other_doc in docs:
        print('"' + doc.text + '"', '"' + other_doc.text + '"', doc.similarity(other_doc))
Explanation: We can vary the word order in sentences and compare them:
End of explanation
nlp = spacy.load('en_core_web_lg')
Explanation: Custom Models
Optimization
End of explanation
from __future__ import unicode_literals, print_function
Explanation: Training Models
This example code for training an NER model is based on the training example in spaCy.
We will import some components from the future module. Read its documentation here.
End of explanation
import random
Explanation: We import the random module for pseudo-random number generation:
End of explanation
from pathlib import Path
Explanation: We import the Path object from the pathlib module:
End of explanation
import spacy
Explanation: We import spaCy:
End of explanation
from spacy.util import minibatch, compounding
Explanation: We also import the minibatch and compounding module from spaCy.utils:
End of explanation
TRAIN_DATA = [
    ("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
    ("I like London and Berlin.", {"entities": [(7, 13, "LOC"), (18, 24, "LOC")]}),
]
Explanation: The training data is formated as JSON:
End of explanation
nlp = spacy.blank("xx")  # create blank Language class
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner, last=True)
Explanation: We created a blank 'xx' model:
End of explanation
for _, annotations in TRAIN_DATA:
    for ent in annotations.get("entities"):
        ner.add_label(ent[2])
Explanation: We add the named entity labels to the NER model:
End of explanation
nlp.begin_training()
Explanation: Assuming that the model is empty and untrained, we reset and initialize the weights randomly using:
End of explanation
pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
Explanation: We would not do this, if the model is supposed to be tuned or retrained on new data.
We get all pipe-names in the model that are not our NER related pipes to disable them during training:
End of explanation
with nlp.disable_pipes(*other_pipes):  # only train NER
    for itn in range(100):
        random.shuffle(TRAIN_DATA)
        losses = {}
        # batch up the examples using spaCy's minibatch
        batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
        for batch in batches:
            texts, annotations = zip(*batch)
            nlp.update(
                texts,  # batch of texts
                annotations,  # batch of annotations
                drop=0.5,  # dropout - make it harder to memorise data
                losses=losses,
            )
        print("Losses", losses)
Explanation: We can now disable the other pipes and train just the NER uing 100 iterations:
End of explanation
for text, _ in TRAIN_DATA:
    doc = nlp(text)
    print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
    print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
Explanation: We can test the trained model:
End of explanation
output_dir = Path("./models/")
Explanation: We can define the output directory where the model will be saved as the models folder in the directory where the notebook is running:
End of explanation
if not output_dir.exists():
    output_dir.mkdir()
nlp.to_disk(output_dir)
Explanation: Save model to output dir:
End of explanation
nlp2 = spacy.load(output_dir)
for text, _ in TRAIN_DATA:
    doc = nlp2(text)
    print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
    print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
Explanation: To make sure everything worked out well, we can test the saved model:
End of explanation
<END_TASK>