# spaCy Tutorial¶

(C) 2018 by Damir Cavar

Version: 1.2, November 2018

This is a tutorial related to the L665 course on Machine Learning for NLP focusing on Deep Learning, Spring 2018 at Indiana University.

## 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:

In [1]:
import spacy

We can load the English NLP pipeline in the following way:

In [2]:

### Tokenization¶

In [3]:
doc = nlp(u'Human ambition is the key to staying ahead of automation.')
for token in doc:
print(token.text)
Human
ambition
is
the
key
to
staying
of
automation
.

### Part-of-Speech Tagging¶

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

In [4]:
doc = nlp(u'Human ambition is the key to staying ahead of automation.')

for token in doc:
print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,
token.shape_, token.is_alpha, token.is_stop)
Human human ADJ JJ compound Xxxxx True False
ambition ambition NOUN NN nsubj xxxx True False
is be VERB VBZ ROOT xx True True
the the DET DT det xxx True True
key key NOUN NN attr xxx True False
to to ADP IN prep xx True True
staying stay VERB VBG pcomp xxxx True False
of of ADP IN prep xx True True
automation automation NOUN NN pobj xxxx True False
. . PUNCT . punct . False False

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:

In [5]:
for token in doc:
[child for child in token.children])
Human compound ambition NOUN []
ambition nsubj is VERB [Human]
is ROOT is VERB [ambition, key, .]
the det key NOUN []
key attr is VERB [the, to]
to prep key NOUN [staying]
. punct is VERB []

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:

In [12]:
for ent in doc.ents:
print(ent.text, ent.start_char, ent.end_char, ent.label_)
John 0 4 PERSON

We can extend the input with some more entities:

In [13]:
doc = nlp(u'John Smith said that Apple Inc. will buy Google in May 2018.')

The corresponding NE-labels are:

In [14]:
for ent in doc.ents:
print(ent.text, ent.start_char, ent.end_char, ent.label_)
John Smith 0 10 PERSON
Apple Inc. 21 31 ORG
May 2018 51 59 DATE

### Pattern Matching in spaCy¶

In [ ]:
from spacy.matcher import Matcher

matcher = Matcher(nlp.vocab)
pattern = [{'LOWER': 'hello'}, {'IS_PUNCT': True}, {'LOWER': 'world'}]

doc = nlp(u'Hello, world! Hello world!')
matches = matcher(doc)
print(matches)

### 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:

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

In [15]:
import spacy

In [6]:
from spacy import displacy

In [17]:

Process an input sentence:

In [17]:
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.")

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 [19]:
displacy.serve(doc, style='dep')
Serving on port 5000...
Using the 'dep' visualizer

Shutting down server on port 5000.

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

In [18]:
displacy.render(doc, style='dep', jupyter=True, options={"distance": 140})

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

In [21]:
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."""

doc = nlp(text)
displacy.render(doc, style='ent', jupyter=True)
Apple ORG decided to fire Tim Cook PERSON and hire somebody called John Doe PERSON as the new CEO. GPE They also discussed a merger with Google ORG . On the long run it seems more likely that Apple ORG will merge with Amazon ORG and Microsoft ORG with Google ORG . The companies will all relocate to GPE Austin GPE in Texas GPE before the end of the century DATE .

## 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:

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 [ ]:
import spacy

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 [ ]:

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

In [ ]:
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:

In [ ]:
for token1 in tokens:
for token2 in tokens:
print(token1, token2, token1.similarity(token2))

We can access the vectors of these objects using the vector attribute:

In [ ]:
tokens = nlp(u'dog cat banana sasquatch')

for token in tokens:
print(token.text, token.has_vector, token.vector_norm, token.is_oov)

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 [ ]:
n = 0
print(tokens[n].text, len(tokens[n].vector), tokens[n].vector)

Here just another example of similarities for some famous words:

In [ ]:
tokens = nlp(u'queen king chef')

for token1 in tokens:
for token2 in tokens:
print(token1, token2, token1.similarity(token2))

### 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:

In [ ]:
import spacy

for token in tokens:
print(token.text, token.has_vector, token.vector_norm, token.is_oov)

We can now test for the context:

In [ ]:

dog = nlp(u"dog")

count = 0
for doc in [doc1, doc2, doc3]:
lab = doc[1]
count += 1
print(str(count) + ":", lab.similarity(dog))

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

In [ ]:
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]))

We can vary the word order in sentences and compare them:

In [ ]:
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))

In [ ]: