Introduction to Natural Language Processing Source Natural Language

  • Slides: 38
Download presentation
Introduction to Natural Language Processing Source: Natural Language Processing with Python --- Analyzing Text

Introduction to Natural Language Processing Source: Natural Language Processing with Python --- Analyzing Text with the Natural Language Toolkit

Status • We have had three weeks of Object. Oriented Programming in Python –

Status • We have had three weeks of Object. Oriented Programming in Python – Simple I/O, File I/O – Lists, Strings, Tuples, and their methods – Numeric types and operations – Control structures: if, for, while – Function definition and use • Parameters for defining the function, arguments for calling the function

Applying what we have • The first chapter of the NLTK book repeats much

Applying what we have • The first chapter of the NLTK book repeats much of what we have seen • Now in the context of an application domain: Natural Language Processing – Note: there are similar packages for other domains • Book examples in chapter 1 are all done with the interactive python shell

Reasons • What can we achieve by combining simple programming techniques with large quantities

Reasons • What can we achieve by combining simple programming techniques with large quantities of text? • How can we automatically extract key words and phrases that sum up the style and content of a text? • What tools and techniques does the Python programming language provide for such work? • What are some of the interesting challenges of natural language processing? Quote from nltk book Since text can cover any subject area, it is a general interest area to explore in some depth.

The NLTK • The natural language tool kit – modules – datasets – tutorials

The NLTK • The natural language tool kit – modules – datasets – tutorials • Contains: align, app (package), book, ccg (package), chat (package, chunk (package), classify (package), cluster (package), collocations, compat, containers, corpus (package), data, decorators, downloader, draw (package), etree (package), evaluate, examples (package), featstruct, grammar), help, inference (package), internals, lazyimport, metrics (package), misc (package), model (package), olac, parse (package), probability, sem (package), sourcedstring, stem (package), tag (package), text, tokenize (package), toolbox (package), treetransforms, util, yamltags We will not have time to explore all of them, but this gives a full list for further exploration.

NLTK functions • all(. . . ) all(iterable) -> bool – Return True if

NLTK functions • all(. . . ) all(iterable) -> bool – Return True if bool(x) is True for all values x in the iterable. • any(. . . ) any(iterable) -> bool – Return True if bool(x) is True for any x in the iterable.

Using the NLTK >>> import nltk >>> nltk. download() opens a window showing this:

Using the NLTK >>> import nltk >>> nltk. download() opens a window showing this: Do it now

Getting data from the downloaded files • Previously, we used from math import pi

Getting data from the downloaded files • Previously, we used from math import pi – to get something specific from a module • Now, from the nltk. book, we will get the text files we will use – from nltk. book import *

Import the data files Do it now. Then type sent 1 at a >>>

Import the data files Do it now. Then type sent 1 at a >>> import nltk python prompt to see the >>> from nltk. book import * fist sentence of Moby Dick *** Introductory Examples for the NLTK Book *** Loading text 1, . . . , text 9 and sent 1, . . . , sent 9 Type the name of the text or sentence to view it. Repeat for sent 2. . sent 9 to see the first sentence of Type: 'texts()' or 'sents()' to list the materials. text 1: Moby Dick by Herman Melville 1851 each text 2: Sense and Sensibility by Jane Austen 1811 text 3: The Book of Genesis Take note of the collection text 4: Inaugural Address Corpus of texts. Great variety. text 5: Chat Corpus Different ones will be text 6: Monty Python and the Holy Grail useful for different types text 7: Wall Street Journal of exploration text 8: Personals Corpus text 9: The Man Who Was Thursday by G. K. Chesterton 1908 What type of data is each first sentence?

Searching the texts >>> text 9. concordance("sunset") Building index. . . Displaying 14 of

Searching the texts >>> text 9. concordance("sunset") Building index. . . Displaying 14 of 14 matches: E suburb of Saffron Park lay on the sunset side of London , as red and ragged as a cloud of sunset. It was built of a bright brick th bered in that place for its strange sunset. It looked like the end of the wor ival ; it was upon the night of the sunset that his solitude suddenly ended. he Embankment once under a dark red sunset. The red river reflected the red s st seemed of fiercer flame than the sunset it mirrored. It looked like a stre he passionate plumage of the cloudy sunset had been swept away , and a naked m der the sea. The sealed and sullen sunset behind the dark dome of St. Paul ' ming with the colour and quality of sunset. The Colonel suggested that , befo gold. Up this side street the last sunset light shone as sharp and narrow as of gas , which in the full flush of sunset seemed coloured like a sunset cloud. " After all , " he said , " y and quietly , like a long , low , sunset cloud , a long , low house , mellow in the mild light of sunset. All the six friends compared note A concordance shows a word in context

Same word in different texts Moby Dick >>> text 1. concordance("monstrous") Building index. .

Same word in different texts Moby Dick >>> text 1. concordance("monstrous") Building index. . . Displaying 11 of 11 matches: ong the former , one was of a most monstrous size. . This came towards us , ON OF THE PSALMS. " Touching that monstrous bulk of the whale or ork we have r ll over with a heathenish array of monstrous clubs and spears. Some were thick d as you gazed , and wondered what monstrous cannibal and savage could ever hav that has survived the flood ; most monstrous and most mountainous ! That Himmal they might scout at Moby Dick as a monstrous fable , or still worse and more de th of Radney. '" CHAPTER 55 Of the Monstrous Pictures of Whales. I shall ere l ing Scenes. In connexion with the monstrous pictures of whales , I am strongly ere to enter upon those still more monstrous stories of them which are to be fo ght have been rummaged out of this monstrous cabinet there is no telling. But of Whale - Bones ; for Whales of a monstrous size are oftentimes cast up dead u >>> text 2. concordance("monstrous") Building index. . . Displaying 11 of 11 matches: . " Now , Palmer , you shall see a monstrous pretty girl. " He immediately went your sister is to marry him. I am monstrous glad of it , for then I shall have ou may tell your sister. She is a monstrous lucky girl to get him , upon my ho k how you will like them. Lucy is monstrous pretty , and so good humoured and Jennings , " I am sure I shall be monstrous glad of Miss Marianne ' s company usual noisy cheerfulness , " I am monstrous glad to see you -- sorry I could n t however , as it turns out , I am monstrous glad there was never any thing in so scornfully ! for they say he is monstrous fond of her , as well he may. I s possible that she should. " " I am monstrous glad of it. Good gracious ! I hav thing of the kind. So then he was monstrous happy , and talked on some time ab e very genteel people. He makes a monstrous deal of money , and they keep thei >>> Sense and Sensibility

>>> text 1. similar("monstrous") abundant candid careful christian contemptible curious delightfully determined doleful domineering

>>> text 1. similar("monstrous") abundant candid careful christian contemptible curious delightfully determined doleful domineering exasperate fearless few gamesome horrible impalpable imperial lamentable lazy loving >>> text 2. similar("monstrous") Building word-context index. . . very exceedingly heartily so a amazingly as extremely good great remarkably sweet vast >>> Note different sense of the word in the two texts.

Spot check • Choose a word and generate a concordance for it in two

Spot check • Choose a word and generate a concordance for it in two or three texts. • Do you see any difference in meaning? • Look for similar terms in the texts. Not sure what words are in what texts? “<word>” in textn will return true or false Look at the first sentence to get some words that are in the text. Guess. ex: “money” appears in all but text 6 and text 8

Looking at vocabulary >>> len(text 3) 44764 >>> Total number of tokens, includes non

Looking at vocabulary >>> len(text 3) 44764 >>> Total number of tokens, includes non words and repeated words >>> len(set(text 3)) 2789 >>> len(set(text 2)) 6833 >>> What do these numbers mean?

A rough measure >>> of lexical richness float(len(text 2))/float(len(set(text 2 ))) 20. 719449729255086 What

A rough measure >>> of lexical richness float(len(text 2))/float(len(set(text 2 ))) 20. 719449729255086 What does this tell us? >>> On average, a word is used > 20 times >>> from __future__ import division >>> 100*text 2. count("money")/len(text 2) 0. 018364694581002431 >>> What does this tell us? Note two ways to get floating point results when dividing integers

Making life easier >>> def lexical_diversity(text): . . . return len(text) / len(set(text)). .

Making life easier >>> def lexical_diversity(text): . . . return len(text) / len(set(text)). . . >>> def percentage(count, total): . . . return 100*count/total. . . >>> lexical_diversity(text 2) 20. 719449729255086 >>> percentage(text 2. count('money'), len(text 2)) 0. 018364694581002431 >>>

Spot check 1. Modify the function percentage so that you only have to pass

Spot check 1. Modify the function percentage so that you only have to pass it the name of the text and the word to count – the new call will look like this: – percentage(text 2, “money”) 2. In which of the texts is “money” most dominant? – Where is it least dominant? – What are the percentages for each text?

Indexing the texts • Each of the texts is a list, and so all

Indexing the texts • Each of the texts is a list, and so all our list methods work, including slicing: The first 101 elements in the list for text 2 (Sense and Sensibility) Note that the first element is itself a list. >>> text 2[0: 100] ['[', 'Sense', 'and', 'Sensibility', 'by', 'Jane', 'Austen', '1811', ']', 'CHAPTER', '1', 'The', 'family', 'of', 'Dashwood', 'had', 'long', 'been', 'settled', 'in', 'Sussex', 'Their', 'estate', 'was', 'large', ', ', 'and', 'their', 'residence', 'was', 'at', 'Norland', 'Park', ', ', 'in', 'the', 'centre', 'of', 'their', 'property', ', ', 'where', ', ', 'for', 'many', 'generations', ', ', 'they', 'had', 'lived', 'in', 'so', 'respectable', 'a', 'manner', 'as', 'to', 'engage', 'the', 'general', 'good', 'opinion', 'of', 'their', 'surrounding', 'acquaintance', 'The', 'late', 'owner', 'of', 'this', 'estate', 'was', 'a', 'single', 'man', ', ', 'who', 'lived', 'to', 'a', 'very', 'advanced', 'age', ', ', 'and', 'who', 'for', 'many', 'years', 'of', 'his', 'life', ', ', 'had', 'a', 'constant', 'companion'] >>>

Text index • We can see what is at a position: >>> text 2[302]

Text index • We can see what is at a position: >>> text 2[302] 'devolved’ • And where a word appears: >>> text 2. index('marriage') 255 >>> Remember that indexing begins at 0 and the index tells how far removed you are from the initial element.

Strings • Each of the elements in each of the text lists is a

Strings • Each of the elements in each of the text lists is a string, and all the string methods apply.

Frequency distributions >>> fdist 1=Freq. Dist(text 1) >>> fdist 1 <Freq. Dist with 260819

Frequency distributions >>> fdist 1=Freq. Dist(text 1) >>> fdist 1 <Freq. Dist with 260819 outcomes> >>> vocabulary 1=fdist 1. keys() >>> vocabulary 1[: 50] [', ', 'the', 'of', 'and', 'a', 'to', '; ', 'in', 'that', "'", '-', 'his', 'it', 'I', 's', 'is', 'he', 'with', 'was', '"', 'all', 'for', 'this', '!', 'at', 'by', 'but', 'not', '--', 'him', 'from', 'be', 'on', 'so', 'whale', 'one', 'you', 'had', 'have', 'there', 'But', 'or', 'were', 'now', 'which', '? ', 'me', 'like'] >>> These are the 50 most common tokens in the text of Moby Dick. Many of these are not useful in characterizing the text. We call them “stop words” and will see how to eliminate them from consideration later.

More precise specification • Consider the mathematical expression • Python implementation is – [w

More precise specification • Consider the mathematical expression • Python implementation is – [w for w in V if p(w)] List comprehension – we saw it first last week >>> Austen. Voc=set(text 2) >>> long_words_2=[w for w in Austen. Voc if len(w) >15] >>> long_words_2 ['incomprehensible', 'disqualifications', 'disinterestedness', 'companionableness'] >>>

Add to the condition fdist 2=Freq. Dist(text 2) >>> long_words_2=sorted([w for w in Austen.

Add to the condition fdist 2=Freq. Dist(text 2) >>> long_words_2=sorted([w for w in Austen. Voc if len(w) >12 and fdist 2[w]>5]) >>> long_words_2 ['Somersetshire', 'accommodation', 'circumstances', 'communication', 'consciousness', 'consideration', 'disappointment', 'distinguished', 'embarrassment', 'encouragement', 'establishment', 'extraordinary', 'inconvenience', 'indisposition', 'neighbourhood', 'unaccountable', 'uncomfortable', 'understanding', 'unfortunately'] So, our if p(w) can be as complex as we need

Spot check • Find all the words longer than 12 characters, which occur at

Spot check • Find all the words longer than 12 characters, which occur at least 5 times, in each of the texts. – How well do they give you a sense of the texts?

Collocations and Bigrams • Sometimes a word by itself is not representative of its

Collocations and Bigrams • Sometimes a word by itself is not representative of its role in a text. It is only with a companion word that we get the intended sense. – red wine – high horse – sign of hope • Bigrams are two word combinations – not all bigrams are useful, of course – len(bigrams(text 2)) == 141575 • including “and among”, “they could” , … • Collocations provides bigrams that include uncommon words – words that might be significant in the text. – text 2. collocations has 20 pairs

>>> colloc 2=text 2. collocations() Colonel Brandon; Sir John; Lady Middleton; Miss Dashwood; every

>>> colloc 2=text 2. collocations() Colonel Brandon; Sir John; Lady Middleton; Miss Dashwood; every thing; thousand pounds; dare say; Miss Steeles; said Elinor; Miss Steele; every body; John Dashwood; great deal; Harley Street; Berkeley Street; Miss Dashwoods; young man; Combe Magna; every day; next morning >>> [len(w) for w in text 2] [1, 5, 3, 11, 2, 4, 6, 4, 1, 7, 1, 3, 6, 2, 8, 3, 4, 4, 7, 2, 6, 1, 5, 6, 3, 5, 1, 3, 5, 9, 3, 2, 7, 4, 1, 2, 3, 6, 2, 5, 8, 1, 5, 1, 3, 4, 11, 1, 4, 3, 5, 2, 2, 11, 1, 6, 2, 2, 6, 3, 7, 4, 7, 2, 5, 11, 12, 1, 3, 4, 5, 2, 4, 6, 3, 1, 3, 5, 2, 1, 4, 8, 3, 1, 3, 3, 3, 4, 5, 2, 3, 4, 1, 3, 1, 8, 9, 3, 11, 2, 3, 6, 1, 3, 3, 5, 1, 5, 8, 3, 5, 6, 3, 3, 1, 8, … For each word in text 2, return its length >>> fdist 2=Freq. Dist([len(w) for w in text 2]) >>> fdist 2 <Freq. Dist with 141576 outcomes> >>> fdist 2. keys() There are 141, 576 words, [3, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16] each with a length. But >>> there are only 17 different word lengths.

>>> fdist 2. items() [(3, 28839), (2, 24826), (1, 23009), (4, 21352), (5, 11438),

>>> fdist 2. items() [(3, 28839), (2, 24826), (1, 23009), (4, 21352), (5, 11438), (6, 9507), (7, 8158), (8, 5676), (9, 3736), (10, 2596), (11, 1278), (12, 711), (13, 334), (14, 87), (15, 24), (17, 3), (16, 2)] >>> There are 28, 839 3 -letter words in Sense and Sensibility (not unique words, necessarily) >>> fdist 2. keys() [3, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16] >>> fdist 2. items() [(3, 28839), (2, 24826), (1, 23009), (4, 21352), (5, 11438), (6, 9507), (7, 8158), (8, 5676), (9, 3736), (10, 2596), (11, 1278), (12, 711), (13, 334), (14, 87), (15, 24), (17, 3), (16, 2)] >>> fdist 2. max() 3 >>> fdist 2[3] 28839 There are 28, 839 3 -letter words and 334 13>>> fdist 2[13] letter words in Sense and Sensibility 334 >>>

Table 1. 2 – Freq. Dist functions Example Descripiton fdist = Freq. Dist(samples) create

Table 1. 2 – Freq. Dist functions Example Descripiton fdist = Freq. Dist(samples) create a frequency distribution containing the given samples fdist. inc(sample) increment the count for this sample fdist['monstrous'] count of the number of times a given sample occurred fdist. freq(‘monstrous’) frequency of a given sample fdist. N() total number of samples fdist. keys() The samples sorted in order of decreasing frequency for sample in fdist: iterate over the samples, in order of decreasing frequency fdist. max() sample with the greatest count fdist. tabulate() tabulate the frequency distribution fdist. plot() graphical plot of the frequency distribution fdist. plot(cumulative=True) cumulative plot of the frequency distribution fdist 1<fdist 2 test if samples in fdist 1 occur less frequently than in fdist 2

Conditionals We have seen conditionals and loop statements. These are some special functions for

Conditionals We have seen conditionals and loop statements. These are some special functions for work on text Function s. startswith(t) s. endswith(t) t in s s. islower() s. isupper() s. isalpha() s. isalnum() s. isdigit() s. istitle() Meaning test if s starts with t test if s ends with t test if t is contained inside s test if all cased characters in s are lowercase test if all cased characters in s are uppercase test if all characters in s are alphabetic test if all characters in s are alphanumeric test if all characters in s are digits test if s is titlecased (all words in s have initial capitals)

Spot check From the NLTK book: Run the following examples and explain what is

Spot check From the NLTK book: Run the following examples and explain what is happening. Then make up some tests of your own. >>> sorted([w for w in set(text 7) if '-' in w and 'index' in w]) >>> sorted([wd for wd in set(text 3) if wd. istitle() and len(wd) > 10]) >>> sorted([w for w in set(sent 7) if not w. islower()]) >>> sorted([t for t in set(text 2) if 'cie' in t or 'cei' in t])

Ending the double count of words • The count of words from the various

Ending the double count of words • The count of words from the various texts was flawed. How? • We had >>> len(text 1) 260819 >>> len(set(text 1)) 19317 >>> len(set([word. lower() for word in text 1])) 17231 >>> • What’s the problem? How do we fix it? >>> len(set([word. lower() for word in text 1 if word. isalpha()])) 16948 >>>

Nested loops and loops with conditions >>> for token in sent 1: . .

Nested loops and loops with conditions >>> for token in sent 1: . . . if token. islower(): . . . print token, 'is a lowercase word'. . . elif token. istitle(): . . . print token, 'is a titlecase word'. . . else: . . . print token, 'is punctuation'. . . Call is a titlecase word me is a lowercase word Ishmael is a titlecase word. is punctuation >>> • Follow what happens.

Another example >>> tricky = sorted([w for w in set(text 2) if 'cie' in

Another example >>> tricky = sorted([w for w in set(text 2) if 'cie' in w or 'cei' in w]) >>> for word in tricky: . . . print word, ancient ceiling conceited conceive conscience conscientiously deceitful deceive. . . >>>

Automatic Text Understanding • See section 1. 5 – Word sense disambiguation a. b.

Automatic Text Understanding • See section 1. 5 – Word sense disambiguation a. b. c. The lost children were found by the searchers (agentive) The lost children were found by the mountain (locative) The lost children were found by the afternoon (temporal) – Pronoun resolution a. b. c. The thieves stole the paintings. They were subsequently sold. The thieves stole the paintings. They were subsequently caught. The thieves stole the paintings. They were subsequently found.

Generating text! >>> text 4. generate() Building ngram index. . . Fellow - Citizens

Generating text! >>> text 4. generate() Building ngram index. . . Fellow - Citizens : Under Providence I have given freedom new reach , and maintain lasting peace -- based on righteousness and justice. There was this reason only why the cotton - producing States should be promoted by just and abundant society , on just principles. These later years have elapsed , and civil war. More than this , we affirm a new beginning is a destiny. May Congress prohibit slavery in the workshop , in translating humanity ' s strongest , but we have adopted , and fear of God. And , in each >>> An inaugural address? ? -- MIT hoax – conference submission

Translation Babel> How long before the next flight to Alice Springs? Babel> german Babel>

Translation Babel> How long before the next flight to Alice Springs? Babel> german Babel> run 0> How long before the next flight to Alice Springs? 1> Wie lang vor dem folgenden Flug zu Alice Springs? 2> How long before the following flight to Alice jump? 3> Wie lang vor dem folgenden Flug zu Alice springen Sie? 4> How long before the following flight to Alice do you jump? 5> Wie lang, bevor der folgende Flug zu Alice tun, Sie springen? 6> How long, before the following flight to Alice does, do you jump? 7> Wie lang bevor der folgende Flug zu Alice tut, tun Sie springen? 8> How long before the following flight to Alice does, do you jump? 9> Wie lang, bevor der folgende Flug zu Alice tut, tun Sie springen? 10> How long, before the following flight does to Alice, do do you jump? 11> Wie lang bevor der folgende Flug zu Alice tut, Sie tun Sprung? 12> How long before the following flight does leap to Alice, does you? Babel>

Jeopardy and Watson The ultimate example of a machine and language http: //www. youtube.

Jeopardy and Watson The ultimate example of a machine and language http: //www. youtube. com/watch? v=xm 8 i. Ujzg. PTg&feature=related http: //www. youtube. com/watch? v=7 h 4 ba. BEi 0 i. A&feature=related -- the strange response http: //www. youtube. com/watch? src_vid=7 h 4 ba. BEi 0 i. A&feature=iv&v=l. IM 7 O_b. RNg&annotation_id=annotation_383798#t=3 m 11 s Explanation of the strange response