We can tokenize and part of speech tag the individual tokens using the following code:

In [ ]:

doc=nlp(u'John said yesterday that Mary bought a new car for her older son.')fortokenindoc:print(token.text,token.lemma_,token.pos_,token.tag_,token.dep_,token.shape_,token.is_alpha,token.is_stop)

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.

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.

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=70%, height=70%>

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.

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.

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.

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.

doc=nlp(u'John said yesterday that Mary bought a new car for her older son.')

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.

In [ ]:

displacy.serve(doc,style='dep')

Instead of serving the graph, one can render it directly into a Jupyter Notebook:

In addition to the visualization of the Dependency Trees, we can visualize named entity annotations:

In [ ]:

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 Applewill merge with Amazon and Microsoft with Google. The companies will all relocate toAustin in Texas before the end of the century."""doc=nlp(text)displacy.render(doc,style='ent',jupyter=True)

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:

In [1]:

importspacy

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:

In [2]:

# nlp = spacy.load('en_core_web_lg')nlp=spacy.load('en')

We can process a list of words by the pipeline using the nlp object:

In [3]:

tokens=nlp(u'dog cat banana')

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:

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:

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:

doc1=nlp(u"The labrador barked.")doc2=nlp(u"The labrador swam.")doc3=nlp(u"the labrador people live in canada.")count=0fordocin[doc1,doc2,doc3]:lab=doc[1]dog=nlp(u"dog")count+=1print(str(count)+":",lab.similarity(dog))

1: 6.34167995391e+16
2: 6.33305619273e+16
3: 0.00345767822817

Using this strategy we can compute document or text similarities as well:

In [11]:

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."))forxinrange(len(docs)):foryinrange(len(docs)):print(x,y,docs[x].similarity(docs[y]))