{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "# Boring preliminaries\n", "%pylab inline\n", "import re\n", "import math\n", "import string\n", "from collections import Counter\n", "from __future__ import division" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Populating the interactive namespace from numpy and matplotlib\n" ] } ], "prompt_number": 63 }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

# Statistical Natural Language Processing in Python.\n", "or\n", "How To Do Things With Words. And Counters.\n", "or\n", "Everything I Needed to Know About NLP I learned From Sesame Street.\n", "Except Kneser-Ney Smoothing.\n", "The Count Didn't Cover That.\n", "\n", " \n", "*One, two, three, ah, ah, ah!* — The Count\n", "

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(1) Data: Text and Words\n", "========\n", "\n", "Before we can do things with words, we need some words. First we need some *text*, possibly from a *file*. Then we can break the text into words. I happen to have a big text called [big.txt](file:///Users/pnorvig/Documents/ipynb/big.txt). We can read it, and see how big it is (in characters):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "TEXT = file('big.txt').read()\n", "len(TEXT)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 64, "text": [ "6488409" ] } ], "prompt_number": 64 }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, six million characters.\n", "\n", "Now let's break the text up into words (or more formal-sounding, *tokens*). For now we'll ignore all the punctuation and numbers, and anything that is not a letter." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def tokens(text):\n", " \"List all the word tokens (consecutive letters) in a text. Normalize to lowercase.\"\n", " return re.findall('[a-z]+', text.lower()) " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 69 }, { "cell_type": "code", "collapsed": false, "input": [ "tokens('This is: A test, 1, 2, 3, this is.')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 73, "text": [ "['this', 'is', 'a', 'test', 'this', 'is']" ] } ], "prompt_number": 73 }, { "cell_type": "code", "collapsed": false, "input": [ "WORDS = tokens(BIG)\n", "len(WORDS)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 70, "text": [ "1105211" ] } ], "prompt_number": 70 }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, a million words. Here are the first 10:\n", "\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(WORDS[:10])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['the', 'project', 'gutenberg', 'ebook', 'of', 'the', 'adventures', 'of', 'sherlock', 'holmes']\n" ] } ], "prompt_number": 68 }, { "cell_type": "markdown", "metadata": {}, "source": [ "(2) Models: Bag of Words\n", "====\n", "\n", "The list WORDS is a list of the words in the TEXT, but it can also serve as a *generative model* of text. We know that language is very complicated, but we can create a simplified model of language that captures part of the complexity. In the *bag of words* model, we ignore the order of words, but maintain their frequency. Think of it this way: take all the words from the text, and throw them into a bag. Shake the bag, and then generating a sentence consists of pulling words out of the bag one at a time. Chances are it won't be grammatical or sensible, but it will have words in roughly the right proportions. Here's a function to sample an *n* word sentence from a bag of words:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def sample(bag, n=10):\n", " \"Sample a random n-word sentence from the model described by the bag of words.\"\n", " return ' '.join(random.choice(bag) for _ in range(n))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 82 }, { "cell_type": "code", "collapsed": false, "input": [ "sample(WORDS)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 85, "text": [ "'of with head the us underneath the affability cannon of'" ] } ], "prompt_number": 85 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another representation for a bag of words is a Counter, which is a dictionary of {'word': count} pairs. For example," ] }, { "cell_type": "code", "collapsed": false, "input": [ "Counter(tokens('Is this a test? It is a test!'))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 23, "text": [ "Counter({'a': 2, 'is': 2, 'test': 2, 'this': 1, 'it': 1})" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "A Counter is like a dict, but with a few extra methods. Let's make a Counter for the big list of WORDS and get a feel for what's there:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "COUNTS = Counter(WORDS)\n", "\n", "print COUNTS.most_common(10)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[('the', 80029), ('of', 40025), ('and', 38312), ('to', 28766), ('in', 22047), ('a', 21155), ('that', 12512), ('he', 12401), ('was', 11410), ('it', 10681)]\n" ] } ], "prompt_number": 93 }, { "cell_type": "code", "collapsed": false, "input": [ "for w in tokens('the rare and neverbeforeseen words'):\n", " print COUNTS[w], w" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "80029 the\n", "83 rare\n", "38312 and\n", "0 neverbeforeseen\n", "460 words\n" ] } ], "prompt_number": 92 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In 1935, linguist George Zipf noted that in any big text, the *n*th most frequent word appears with a frequency of about 1/*n* of the most frequent word. He get's credit for *Zipf's Law*, even though Felix Auerbach made the same observation in 1913. If we plot the frequency of words, most common first, on a log-log plot, they should come out as a straight line if Zipf's Law holds. Here we see that it is a fairly close fit:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "M = COUNTS['the']\n", "yscale('log'); xscale('log'); title('Frequency of n-th most frequent word and 1/n line.')\n", "plot([c for (w, c) in COUNTS.most_common()])\n", "plot([M/i for i in range(1, len(COUNTS)+1)]);" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "display_data", "png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAEPCAYAAACukxSbAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XdYU9cbB/Bv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SNPk3f8E6n\nTp0QEREh7TAaBQ8PD4SHh2PFihWCbkV5ZGZmhs2bN2Pz5s2IjY2VdjhSt2rVKowePVraYUidgoIC\n1NTU0Lx5cxgZGYm2T0MGRNM3vFObumjq6lIXK1euhL+/vyTDbHC1rYf9+/ejX79+GDVqlKRDbXC1\nqYv4+HiYm5ujbdu20gi1wdWmLpycnHDw4EHMmDEDq1evFu0J6jXKvwbJycksPT290kVdjDFmbW3N\nkpKSWHZ2NjM1NWU5OTns2LFjbPfu3Ywxxvz8/BoyLKmoTV2UGzFihKTDlAhR6+Lp06esrKyMzZ49\nmyUkJEgp2oZTl/cEY4y5u7tLMkyJqE1dLFiwgM2YMYMNHDiQeXh4sLKyMilF3TDq8r7Izc1l3t7e\nIh2/QS/OcnJyQnZ2dqX7Kk7fAEAwfYOrqysWLFiAkydPSnT6BkmpTV307t0b8+fPx4ULF7By5UrM\nmTNH0uE2KFHrIjU1FTdv3sSxY8fw+vVr3Lhxo0ll+7V5T6ipqWHPnj1gjDXJcz21qYulS5cCALZt\n24a2bduCx+NJNNaGVpu6KC4uxuHDh1FaWoqAgACRji/xK3LPnj0LMzMzwba5uTlSU1MxZMgQ0X+e\nNBHV1UVYWJgUI5O8qupiyZIlmDp1qhQjk6zq6sHZ2VmKkUledZ8PAJg4caK0QpO46t4Xn332Wa2O\n1WhO5BJCCGl4Em/0afqGd6gu3qG64FA9vEN18Y4460LijT5N3/AO1cU7VBccqod3qC7eEWtdiPOs\n8/vGjBnD2rdvz5o1a8Z0dXVZVFQUY4yxxMREZmZmxjp37sxCQ0MbMoRGg+riHaoLDtXDO1QX7zR0\nXdA0DIQQIkfoRC4hhMgRavQJIUSOUKNPCCFyhBp9QgiRI9ToE0KIHKFGnxBC5Ag1+oQQIkeo0SeE\nEDlCjT4hhMiR/wE9/sD6YxSWVQAAAABJRU5ErkJggg==\n", "text": [ "" ] } ], "prompt_number": 97 }, { "cell_type": "markdown", "metadata": {}, "source": [ "(3) Task: Spelling Correction\n", "========\n", "\n", "Given a word *w*, find the most likely correction *c* = correct(*w*).\n", "\n", "**Approach:** Try all candidate words *c* that are known words that are near *w*. Choose the most likely one.\n", "\n", "How to balance *near* and *likely*?\n", "\n", "For now, in a trivial way: always prefer nearer, but when there is a tie on nearness, use the word with the highest WORDS count. Measure nearness by *edit distance*: the minimum number of deletions, transpositions, insertions, or replacements of characters. By trial and error, we determine that going out to edit distance 2 will give us reasonable results. Then we can define correct(*w*):\n", " \n", " \n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def correct(word):\n", " \"Find the best spelling correction for this word.\"\n", " # Prefer edit distance 0, then 1, then 2; otherwise default to word itself.\n", " candidates = (known(edits0(word)) or \n", " known(edits1(word)) or \n", " known(edits2(word)) or \n", " [word])\n", " return max(candidates, key=COUNTS.get)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 110 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The functions known and edits0 are easy; and edits2 is easy if we assume we have edits1:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def known(words):\n", " \"Return the subset of words that are actually in the dictionary.\"\n", " return {w for w in words if w in COUNTS}\n", "\n", "def edits0(word): \n", " \"Return all strings that are zero edits away from word (i.e., just word itself).\"\n", " return {word}\n", "\n", "def edits2(word):\n", " \"Return all strings that are two edits away from this word.\"\n", " return {e2 for e1 in edits1(word) for e2 in edits1(e1)}" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 111 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now for edits1(word): the set of candidate words that are one edit away. For example, given \"wird\", this would include \"weird\" (inserting an e) and \"word\" (replacing a i with a o), and also \"iwrd\" (transposing w and i; then known can be used to filter this out of the set of final candidates). How could we get them? One way is to *split* the original word in all possible places, each split forming a *pair* of words, (a, b), before and after the place, and at each place, either delete, transpose, replace, or insert a letter:\n", "\n", "\n", "
 pairs: \u00d8+wird w+ird wi+rd wir+d wird+\u00d8 Notes: (a, b) pair\n", " deletions: \u00d8+ird w+rd wi+d wir+\u00d8 Delete first char of b\n", " transpositions: \u00d8+iwrd w+rid wi+dr Swap first two chars of b\n", " replacements: \u00d8+?ird w+?rd wi+?d wir+? Replace char at start of b\n", " insertions: \u00d8+?+wird w+?+ird wi+?+rd wir+?+d wird+?+\u00d8 Insert char between a and b\n", "
" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def edits1(word):\n", " \"Return all strings that are one edit away from this word.\"\n", " pairs = splits(word)\n", " deletes = [a+b[1:] for (a, b) in pairs if b]\n", " transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) > 1]\n", " replaces = [a+c+b[1:] for (a, b) in pairs for c in alphabet if b]\n", " inserts = [a+c+b for (a, b) in pairs for c in alphabet]\n", " return set(deletes + transposes + replaces + inserts)\n", "\n", "def splits(word):\n", " \"Return a list of all possible (first, rest) pairs that comprise word.\"\n", " return [(word[:i], word[i:]) \n", " for i in range(len(word)+1)]\n", "\n", "alphabet = 'abcdefghijklmnopqrstuvwxyz'" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 100 }, { "cell_type": "code", "collapsed": false, "input": [ "splits('wird')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 101, "text": [ "[('', 'wird'), ('w', 'ird'), ('wi', 'rd'), ('wir', 'd'), ('wird', '')]" ] } ], "prompt_number": 101 }, { "cell_type": "code", "collapsed": false, "input": [ "print edits0('wird')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "set(['wird'])\n" ] } ], "prompt_number": 103 }, { "cell_type": "code", "collapsed": false, "input": [ "print edits1('wird')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "set(['wirdh', 'wirdw', 'jird', 'wiid', 'wirj', 'wiprd', 'rird', 'wkird', 'wiqrd', 'wrird', 'wisrd', 'zwird', 'wiqd', 'wizrd', 'wirs', 'wrd', 'wqird', 'tird', 'wirdp', 'wrrd', 'wzrd', 'wiad', 'nird', 'wirsd', 'wixd', 'wxird', 'lird', 'eird', 'wmird', 'wihd', 'wirp', 'lwird', 'wirzd', 'widrd', 'wxrd', 'ewird', 'wirdx', 'wirkd', 'hwird', 'wipd', 'wirnd', 'uwird', 'wirz', 'mwird', 'wjrd', 'wirjd', 'wirrd', 'wirdd', 'wsird', 'bwird', 'wcrd', 'xwird', 'wdird', 'wibrd', 'wikd', 'wiryd', 'wiord', 'gird', 'wtird', 'wbrd', 'nwird', 'wlrd', 'wgird', 'wmrd', 'wirf', 'wirg', 'wird', 'wire', 'wirb', 'wirc', 'wira', 'wkrd', 'wiro', 'wirl', 'wirm', 'iird', 'wirk', 'wirh', 'wiri', 'wirv', 'wirw', 'wirt', 'wiru', 'wirr', 'wicd', 'cird', 'wirq', 'wirqd', 'wizd', 'wirhd', 'ird', 'bird', 'wirx', 'wiry', 'wvrd', 'widr', 'wprd', 'wirad', 'wijd', 'wirxd', 'uird', 'wirdb', 'qwird', 'dird', 'wnrd', 'wjird', 'gwird', 'whrd', 'wtrd', 'woird', 'rwird', 'wurd', 'wijrd', 'witrd', 'wwrd', 'dwird', 'vwird', 'wibd', 'wiyd', 'wicrd', 'weird', 'yird', 'wiwrd', 'wirdv', 'wirdu', 'wid', 'wirds', 'wirdr', 'sird', 'wirbd', 'wirdq', 'wirdy', 'wivrd', 'wirdg', 'wirdf', 'wirde', 'wiud', 'wirdc', 'wir', 'wirda', 'wfird', 'kwird', 'wirdn', 'wirdm', 'wirdl', 'wirdk', 'wirdj', 'wiird', 'wnird', 'wiurd', 'wied', 'aird', 'wirod', 'wpird', 'wcird', 'wzird', 'jwird', 'wirdo', 'wsrd', 'wimd', 'wirwd', 'mird', 'fird', 'wuird', 'wirdt', 'wired', 'wirgd', 'wirfd', 'witd', 'wfrd', 'wyrd', 'wihrd', 'zird', 'ward', 'wilrd', 'widd', 'iwrd', 'hird', 'word', 'wisd', 'wvird', 'pird', 'wlird', 'wyird', 'wdrd', 'werd', 'wild', 'oird', 'wirid', 'wgrd', 'wirvd', 'wiod', 'wirud', 'wircd', 'wiyrd', 'wigrd', 'wixrd', 'wiard', 'vird', 'wiwd', 'wigd', 'wirmd', 'swird', 'wierd', 'xird', 'qird', 'waird', 'wqrd', 'kird', 'cwird', 'wirtd', 'wirdz', 'awird', 'fwird', 'wirpd', 'wifrd', 'pwird', 'owird', 'wivd', 'wimrd', 'iwird', 'winrd', 'wirdi', 'wrid', 'wifd', 'wirld', 'wwird', 'ywird', 'wirn', 'wbird', 'whird', 'wikrd', 'wind', 'twird'])\n" ] } ], "prompt_number": 102 }, { "cell_type": "code", "collapsed": false, "input": [ "print len(edits2('wird'))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "24254\n" ] } ], "prompt_number": 104 }, { "cell_type": "code", "collapsed": false, "input": [ "map(correct, tokens('Speling errurs in somethink. Whutever; unusuel misteakes everyware?'))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 112, "text": [ "['spelling',\n", " 'errors',\n", " 'in',\n", " 'something',\n", " 'whatever',\n", " 'unusual',\n", " 'mistakes',\n", " 'everywhere']" ] } ], "prompt_number": 112 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Can we make the output prettier than that?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def correct_text(text):\n", " \"Correct all the words within a text, returning the corrected text.\"\n", " return re.sub('[a-zA-Z]+', correct_match, text)\n", "\n", "def correct_match(match):\n", " \"Spell-correct word in match, and preserve proper upper/lower/title case.\"\n", " word = match.group()\n", " return case_of(word)(correct(word.lower()))\n", "\n", "def case_of(text):\n", " \"Return the case-function appropriate for text: upper, lower, title, or just str.\"\n", " return (str.upper if text.isupper() else\n", " str.lower if text.islower() else\n", " str.title if text.istitle() else\n", " str)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 113 }, { "cell_type": "code", "collapsed": false, "input": [ "map(case_of, ['UPPER', 'lower', 'Title', 'CamelCase'])" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 114, "text": [ "[,\n", " ,\n", " ,\n", " str]" ] } ], "prompt_number": 114 }, { "cell_type": "code", "collapsed": false, "input": [ "correct_text('Speling Errurs IN somethink. Whutever; unusuel misteakes?')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 115, "text": [ "'Spelling Errors IN something. Whatever; unusual mistakes?'" ] } ], "prompt_number": 115 }, { "cell_type": "code", "collapsed": false, "input": [ "correct_text('Audiance sayzs: tumblr ...')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 116, "text": [ "'Audience says: tumbler ...'" ] } ], "prompt_number": 116 }, { "cell_type": "markdown", "metadata": {}, "source": [ "So far so good. You can probably think of a dozen ways to make this better. Here's one: in the text \"three, too, one, blastoff!\" we might want to correct \"too\" with \"two\", even though \"too\" is in the dictionary. We can do better if we look at a *sequence* of words, not just an individual word one at a time. But how can we choose the best corrections of a sequence? The ad-hoc approach worked pretty well for single words, but now we could use some real theory ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(4) Theory: From Counts to Probabilities of Word Sequences\n", "===\n", "\n", "We should be able to compute the probability of a word, $P(w)$. We do that with the function pdist, which takes as input a Counter (hat is, a bag of words) and returns a function that acts as a probability distribution over all possible words. In a probability distribution the probability of each word is between 0 and 1, and the sum of the probabilities is 1." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def pdist(counter):\n", " \"Make a probability distribution, given evidence from a Counter.\"\n", " N = sum(counter.values())\n", " return lambda x: counter[x]/N\n", "\n", "P = pdist(COUNTS)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 154 }, { "cell_type": "code", "collapsed": false, "input": [ "for w in tokens('\"The\" is most common word in English'):\n", " print P(w), w" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0.0724106075672 the\n", "0.00884356018896 is\n", "0.000821562579453 most\n", "0.000259678921039 common\n", "0.000269631771671 word\n", "0.0199482270806 in\n", "0.000190913771217 english\n" ] } ], "prompt_number": 155 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, what is the probability of a *sequence* of words? Use the definition of a joint probability:\n", "\n", "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2 \\mid w_1) \\times P(w_3 \\mid w_1 w_2) \\ldots \\times \\ldots P(w_n \\mid w_1 \\ldots w_{n-1})$\n", "\n", "The *bag of words* model assumes that each word is drawn from the bag *independently* of the others. This gives us the wrong approximation:\n", " \n", "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2) \\times P(w_3) \\ldots \\times \\ldots P(w_n)$\n", "\n", " \n", " The statistician George Box said that *All models are wrong, but some are useful.*\n", " \n", "How can we compute $P(w_1 \\ldots w_n)$? We'll use a different function name, Pwords, rather than P, and we compute the product of the individual probabilities:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def Pwords(words):\n", " \"Probability of words, assuming each word is independent of others.\"\n", " return product(Pword(w) for w in words)\n", "\n", "def product(nums):\n", " \"Multiply the numbers together. (Like sum, but with multiplication.)\"\n", " result = 1\n", " for x in nums:\n", " result *= x\n", " return result" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 120 }, { "cell_type": "code", "collapsed": false, "input": [ "tests = ['this is a test', \n", " 'this is a unusual test',\n", " 'this is a neverbeforeseen test']\n", "\n", "for test in tests:\n", " print Pwords(tokens(test)), test" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2.98419543271e-11 this is a test\n", "8.64036404331e-16 this is a unusual test\n", "0.0 this is a neverbeforeseen test\n" ] } ], "prompt_number": 121 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yikes—it seems wrong to give a probability of 0 to the last one; it should just be very small. We'll come back to that later. The other probabilities seem reasonable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(5) Task: Word Segmentation\n", "====\n", "\n", "**Task**: *given a sequence of characters with no spaces separating words, recover the sequence of words.*\n", " \n", "\n", "Why? Languages with no word delimiters: [\u4e0d\u5e26\u7a7a\u683c\u7684\u8bcd](http://translate.google.com/#auto/en/%E4%B8%8D%E5%B8%A6%E7%A9%BA%E6%A0%BC%E7%9A%84%E8%AF%8D)\n", "\n", "In English, sub-genres with no word delimiters ([spelling errors](https://www.google.com/search?q=wordstogether), [URLs](http://speedofart.com)).\n", "\n", "**Approach 1:** Enumerate all candidate segementations and choose the one with highest Pwords\n", "\n", "Problem: how many segmentations are there for an *n*-character text?\n", "\n", "**Approach 2:** Make one segmentation, into a first word and remaining characters. If we assume words are independent \n", "then we can maximize the probability of the first word adjoined to the best segmentation of the remaining characters.\n", " \n", " assert segment('choosespain') == ['choose', 'spain']\n", "\n", " segment('choosespain') ==\n", " max(Pwords(['c'] + segment('hoosespain')),\n", " Pwords(['ch'] + segment('oosespain')),\n", " Pwords(['cho'] + segment('osespain')),\n", " Pwords(['choo'] + segment('sespain')),\n", " ...\n", " Pwords(['choosespain'] + segment('')))\n", " \n", " \n", " \n", "To make this somewhat efficient, we need to avoid re-computing the segmentations of the remaining characters. This can be done explicitly by *dynamic programming* or implicitly with *memoization*. Also, we shouldn't consider all possible lengths for the first word; we can impose a maximum length. What should it be? A little more than the longest word seen so far." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def memo(f):\n", " \"Memoize function f, whose args must all be hashable.\"\n", " cache = {}\n", " def fmemo(*args):\n", " if args not in cache:\n", " cache[args] = f(*args)\n", " return cache[args]\n", " fmemo.cache = cache\n", " return fmemo" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 156 }, { "cell_type": "code", "collapsed": false, "input": [ "max(len(w) for w in COUNTS)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 157, "text": [ "18" ] } ], "prompt_number": 157 }, { "cell_type": "code", "collapsed": false, "input": [ "def splits(text, start=0, L=20):\n", " \"Return a list of all (first, rest) pairs; start <= len(first) <= L.\"\n", " return [(text[:i], text[i:]) \n", " for i in range(start, min(len(text), L)+1)]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 160 }, { "cell_type": "code", "collapsed": false, "input": [ "print splits('word')\n", "print splits('reallylongtext', 1, 4)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[('', 'word'), ('w', 'ord'), ('wo', 'rd'), ('wor', 'd'), ('word', '')]\n", "[('r', 'eallylongtext'), ('re', 'allylongtext'), ('rea', 'llylongtext'), ('real', 'lylongtext')]\n" ] } ], "prompt_number": 161 }, { "cell_type": "code", "collapsed": false, "input": [ "@memo\n", "def segment(text):\n", " \"Return a list of words that is the most probable segmentation of text.\"\n", " if not text: \n", " return []\n", " else:\n", " candidates = ([first] + segment(rest) \n", " for (first, rest) in splits(text, 1))\n", " return max(candidates, key=Pwords)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 162 }, { "cell_type": "code", "collapsed": false, "input": [ "segment('choosespain')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 163, "text": [ "['choose', 'spain']" ] } ], "prompt_number": 163 }, { "cell_type": "code", "collapsed": false, "input": [ "segment('speedofart')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 164, "text": [ "['speed', 'of', 'art']" ] } ], "prompt_number": 164 }, { "cell_type": "code", "collapsed": false, "input": [ "decl = ('wheninthecourseofhumaneventsitbecomesnecessaryforonepeople' +\n", " 'todissolvethepoliticalbandswhichhaveconnectedthemwithanother' +\n", " 'andtoassumeamongthepowersoftheearththeseparateandequalstation' +\n", " 'towhichthelawsofnatureandofnaturesgodentitlethem')" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 165 }, { "cell_type": "code", "collapsed": false, "input": [ "print(segment(decl))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['when', 'in', 'the', 'course', 'of', 'human', 'events', 'it', 'becomes', 'necessary', 'for', 'one', 'people', 'to', 'dissolve', 'the', 'political', 'bands', 'which', 'have', 'connected', 'them', 'with', 'another', 'and', 'to', 'assume', 'among', 'the', 'powers', 'of', 'the', 'earth', 'the', 'separate', 'and', 'equal', 'station', 'to', 'which', 'the', 'laws', 'of', 'nature', 'and', 'of', 'natures', 'god', 'entitle', 'them']\n" ] } ], "prompt_number": 166 }, { "cell_type": "code", "collapsed": false, "input": [ "Pwords(segment(decl))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 172, "text": [ "3.613815636889254e-141" ] } ], "prompt_number": 172 }, { "cell_type": "code", "collapsed": false, "input": [ "Pwords(segment(decl * 2))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 171, "text": [ "1.305966345742529e-281" ] } ], "prompt_number": 171 }, { "cell_type": "code", "collapsed": false, "input": [ "Pwords(segment(decl * 3))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 170, "text": [ "0.0" ] } ], "prompt_number": 170 }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's a problem. We'll come back to it later." ] }, { "cell_type": "code", "collapsed": false, "input": [ "segment('smallandinsignificant')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 173, "text": [ "['small', 'and', 'insignificant']" ] } ], "prompt_number": 173 }, { "cell_type": "code", "collapsed": false, "input": [ "segment('largeandinsignificant')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 174, "text": [ "['large', 'and', 'insignificant']" ] } ], "prompt_number": 174 }, { "cell_type": "code", "collapsed": false, "input": [ "print(Pwords(['large', 'and', 'insignificant']))\n", "print(Pwords(['large', 'and', 'in', 'significant']))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "4.1121373609e-10\n", "1.06638804821e-11\n" ] } ], "prompt_number": 175 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Summary:\n", " \n", "- Looks pretty good!\n", "- The bag-of-words assumption is a limitation.\n", "- Recomputing Pwords on each recursive call is somewhat inefficient.\n", "- Numeric underflow for texts longer than 100 or so words; we'll need to use logarithms, or other tricks.\n" ] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "(6) Data: Mo' Data, Mo' Better" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's move up from millions to *billions and billions* of words. Once we have that amount of data, we can start to look at two word sequences, without them being too sparse. I happen to have data files available in the format of \"word \\t count\", and bigram data in the form of \"word1 word2 \\t count\". Let's arrange to read them in:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def load_counts(filename, sep='\\t'):\n", " \"\"\"Return a Counter initialized from key-value pairs, \n", " one on each line of filename.\"\"\"\n", " C = Counter()\n", " for line in open(filename):\n", " key, count = line.split(sep)\n", " C[key] = int(count)\n", " return C" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 178 }, { "cell_type": "code", "collapsed": false, "input": [ "COUNTS1 = load_counts('count_1w.txt')\n", "COUNTS2 = load_counts('count_2w.txt')\n", "\n", "P1w = pdist(COUNTS1)\n", "P2w = pdist(COUNTS2)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 180 }, { "cell_type": "code", "collapsed": false, "input": [ "print len(COUNTS1), sum(COUNTS1.values())/1e9\n", "print len(COUNTS2), sum(COUNTS2.values())/1e9" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "333333 " ] }, { "output_type": "stream", "stream": "stdout", "text": [ "588.124220187\n", "286358 " ] }, { "output_type": "stream", "stream": "stdout", "text": [ "225.955251755\n" ] } ], "prompt_number": 181 }, { "cell_type": "code", "collapsed": false, "input": [ "COUNTS2.most_common(30)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 183, "text": [ "[('of the', 2766332391),\n", " ('in the', 1628795324),\n", " ('to the', 1139248999),\n", " ('on the', 800328815),\n", " ('for the', 692874802),\n", " ('and the', 629726893),\n", " ('to be', 505148997),\n", " ('is a', 476718990),\n", " ('with the', 461331348),\n", " ('from the', 428303219),\n", " ('by the', 417106045),\n", " ('at the', 416201497),\n", " ('of a', 387060526),\n", " ('in a', 364730082),\n", " ('will be', 356175009),\n", " ('that the', 333393891),\n", " ('do not', 326267941),\n", " ('is the', 306482559),\n", " ('to a', 279146624),\n", " ('is not', 276753375),\n", " ('for a', 274112498),\n", " ('with a', 271525283),\n", " ('as a', 270401798),\n", " (' and', 261891475),\n", " ('of this', 258707741),\n", " (' the', 258483382),\n", " ('it is', 245002494),\n", " ('can be', 230215143),\n", " ('If you', 210252670),\n", " ('has been', 196769958)]" ] } ], "prompt_number": 183 }, { "cell_type": "markdown", "metadata": {}, "source": [ "(7) Theory and Practice: Segmentation With Bigram Data\n", "===\n", "\n", "A less-wrong approximation:\n", " \n", "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2 \\mid w_1) \\times P(w_3 \\mid w_2) \\ldots \\times \\ldots P(w_n \\mid w_{n-1})$\n", "\n", "This is called the *bigram* model, and is equivalent to taking a text, cutting it up into slips of paper with two words on them, and having multiple bags, and putting each slip into a bag labelled with the first word on the slip. Then, to generate language, we choose the first word from the original single bag of words, and chose all subsequent words from the bag with the label of the previously-chosen word.\n", "\n", "Let's start by defining the probability of a single discrete event, given evidence stored in a Counter:\n", "\n", "Recall that the less-wrong bigram model approximation to English is:\n", " \n", "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2 \\mid w_1) \\times P(w_3 \\mid w_2) \\ldots \\times \\ldots P(w_n \\mid w_{n-1})$\n", "\n", "where the conditional probability of a word given the previous word is defined as:\n", "\n", "$P(w_n \\mid w_{n-1}) = P(w_{n-1}w_n) / P(w_{n-1})$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def Pwords2(words, prev=''):\n", " \"The probability of a sequence of words, using bigram data, given prev word.\"\n", " return product(cPword(w, (prev if (i == 0) else words[i-1]) )\n", " for (i, w) in enumerate(words))\n", "\n", "# Change Pwords to use P1w (the bigger dictionary) instead of Pword\n", "def Pwords(words):\n", " \"Probability of words, assuming each word is independent of others.\"\n", " return product(P1w(w) for w in words)\n", "\n", "def cPword(word, prev):\n", " \"Conditional probability of word, given previous word.\"\n", " bigram = prev + ' ' + word\n", " if P2w(bigram) > 0 and P1w(prev) > 0:\n", " return P2w(bigram) / P1w(prev)\n", " else: # Average the back-off value and zero.\n", " return P1w(word) / 2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 184 }, { "cell_type": "code", "collapsed": false, "input": [ "print Pwords(tokens('this is a test'))\n", "print Pwords2(tokens('this is a test'))\n", "print Pwords2(tokens('is test a this'))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.78739820006e-10\n", "6.41367629438e-08\n", "1.18028600367e-11\n" ] } ], "prompt_number": 185 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make segment2, we copy segment, and make sure to pass around the previous token, and to evaluate probabilities with Pwords2 instead of Pwords." ] }, { "cell_type": "code", "collapsed": false, "input": [ "@memo \n", "def segment2(text, prev=''): \n", " \"Return best segmentation of text; use bigram data.\" \n", " if not text: \n", " return []\n", " else:\n", " candidates = ([first] + segment2(rest, first) \n", " for (first, rest) in splits(text, 1))\n", " return max(candidates, key=lambda words: Pwords2(words, prev))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 202 }, { "cell_type": "code", "collapsed": false, "input": [ "print segment2('choosespain')\n", "print segment2('speedofart')\n", "print segment2('smallandinsignificant')\n", "print segment2('largeandinsignificant')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['choose', 'spain']\n", "['speed', 'of', 'art']\n", "['small', 'and', 'in', 'significant']\n", "['large', 'and', 'in', 'significant']\n" ] } ], "prompt_number": 190 }, { "cell_type": "code", "collapsed": false, "input": [ "adams = ('faroutintheunchartedbackwatersoftheunfashionableendofthewesternspiral' +\n", " 'armofthegalaxyliesasmallunregardedyellowsun')\n", "print segment(adams)\n", "print segment2(adams)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['far', 'out', 'in', 'the', 'uncharted', 'backwaters', 'of', 'the', 'unfashionable', 'end', 'of', 'the', 'western', 'spiral', 'arm', 'of', 'the', 'galaxy', 'lies', 'a', 'small', 'un', 'regarded', 'yellow', 'sun']\n", "['far', 'out', 'in', 'the', 'uncharted', 'backwaters', 'of', 'the', 'unfashionable', 'end', 'of', 'the', 'western', 'spiral', 'arm', 'of', 'the', 'galaxy', 'lies', 'a', 'small', 'un', 'regarded', 'yellow', 'sun']\n" ] } ], "prompt_number": 193 }, { "cell_type": "code", "collapsed": false, "input": [ "P1w('unregarded')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 194, "text": [ "0.0" ] } ], "prompt_number": 194 }, { "cell_type": "code", "collapsed": false, "input": [ "tolkein = 'adrybaresandyholewithnothinginittositdownonortoeat'\n", "print segment(tolkein)\n", "print segment2(tolkein)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sitdown', 'on', 'or', 'to', 'eat']\n", "['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat']" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 195 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conclusion? Bigram model is a little better, but not much. Hundreds of billions of words still not enough. (Why not trillions?) Could be made more efficient." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(8) Theory: Evaluation\n", "===\n", "\n", "So far, we've got an intuitive feel for how this all works. But we don't have any solid metrics that quantify the results. Without metrics, we can't say if we are doing well, nor if a change is an improvement. In general,\n", "when developing a program that relies on data to help make\n", "predictions, it is good practice to divide your data into three sets:\n", "
\n", "
1. Training set: the data used to create our spelling\n", " model; this was the big.txt file.\n", "
2. Development set: a set of input/output pairs that we can\n", " use to rank the performance of our program as we are developing it.\n", "
3. Test set: another set of input/output pairs that we use\n", " to rank our program after we are done developing it. The\n", " development set can't be used for this purpose—once the\n", " programmer has looked at the development test it is tainted, because\n", " the programmer might modify the program just to pass the development\n", " test. That's why we need a separate test set that is only looked at\n", " after development is done.\n", "
\n", "\n", "For this program, the training data is the word frequency counts, the development set is the examples like \"choosespain\" that we have been playing with, and now we need a test set." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def test_segmenter(segmenter, tests):\n", " \"Try segmenter on tests; report failures; return fraction correct.\"\n", " return sum([test_one_segment(segmenter, test) \n", " for test in tests]), len(tests)\n", "\n", "def test_one_segment(segmenter, test):\n", " words = tokens(test)\n", " result = segmenter(cat(words))\n", " correct = (result == words)\n", " if not correct:\n", " print 'expected', words\n", " print 'got ', result\n", " return correct\n", "\n", "proverbs = (\"\"\"A little knowledge is a dangerous thing\n", " A man who is his own lawyer has a fool for his client\n", " All work and no play makes Jack a dull boy\n", " Better to remain silent and be thought a fool that to speak and remove all doubt;\n", " Do unto others as you would have them do to you\n", " Early to bed and early to rise, makes a man healthy, wealthy and wise\n", " Fools rush in where angels fear to tread\n", " Genius is one percent inspiration, ninety-nine percent perspiration\n", " If you lie down with dogs, you will get up with fleas\n", " Lightning never strikes twice in the same place\n", " Power corrupts; absolute power corrupts absolutely\n", " Here today, gone tomorrow\n", " See no evil, hear no evil, speak no evil\n", " Sticks and stones may break my bones, but words will never hurt me\n", " Take care of the pence and the pounds will take care of themselves\n", " Take care of the sense and the sounds will take care of themselves\n", " The bigger they are, the harder they fall\n", " The grass is always greener on the other side of the fence\n", " The more things change, the more they stay the same\n", " Those who do not learn from history are doomed to repeat it\"\"\"\n", " .splitlines())" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 201 }, { "cell_type": "code", "collapsed": false, "input": [ "test_segmenter(segment, proverbs)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "expected ['sticks', 'and', 'stones', 'may', 'break', 'my', 'bones', 'but', 'words', 'will', 'never', 'hurt', 'me']\n", "got ['stick', 'sandstones', 'may', 'break', 'my', 'bones', 'but', 'words', 'will', 'never', 'hurt', 'me']\n" ] }, { "metadata": {}, "output_type": "pyout", "prompt_number": 203, "text": [ "(19, 20)" ] } ], "prompt_number": 203 }, { "cell_type": "code", "collapsed": false, "input": [ "test_segmenter(segment2, proverbs)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 204, "text": [ "(20, 20)" ] } ], "prompt_number": 204 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This confirms that both segmenters are very good, and that segment2 is slightly better. There is much more that can be done in terms of the variety of tests, and in measuring statistical significance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(9) Theory and Practice: Smoothing\n", "======\n", "\n", "Let's go back to a test we did before, and add some more test cases:\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "tests = ['this is a test', \n", " 'this is a unusual test',\n", " 'this is a nongovernmental test',\n", " 'this is a neverbeforeseen test',\n", " 'this is a zqbhjhsyefvvjqc test']\n", "\n", "for test in tests:\n", " print Pwords(tokens(test)), test" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.78739820006e-10 this is a test\n", "3.78675425278e-15 this is a unusual test\n", "1.31179474235e-16 this is a nongovernmental test\n", "0.0 this is a neverbeforeseen test\n", "0.0 this is a zqbhjhsyefvvjqc test\n" ] } ], "prompt_number": 205 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The issue here is the finality of a probability of zero. Out of the three 15-letter words, it turns out that \"nongovernmental\" is in the dictionary, but if it hadn't been, if somehow our corpus of words had missed it, then the probability of that whole phrase would have been zero. It seems that is too strict; there must be some \"real\" words that are not in our dictionary, so we shouldn't give them probability zero. There is also a question of likelyhood of being a \"real\" word. It does seem that \"neverbeforeseen\" is more English-like than \"zqbhjhsyefvvjqc\", and so perhaps should have a higher probability.\n", "\n", "We can address this by assigning a non-zero probability to words that are not in the dictionary. This is even more important when it comes to multi-word phrases (such as bigrams), because it is more likely that a legitimate one will appear that has not been observed before.\n", "\n", "We can think of our model as being overly spiky; it has a spike of probability mass wherever a word or phrase occurs in the corpus. What we would like to do is *smooth* over those spikes so that we get a model that does not depend on the details of our corpus. The process of \"fixing\" the model is called *smoothing*.\n", "\n", "For example, Laplace was asked what's the probability of the sun rising tomorrow. From data that it has risen $n/n$ times for the last *n* days, the maximum liklihood estimator is 1. But Laplace wanted to balance the data with the possibility that tomorrow, either it will rise or it won't, so he came up with $(n + 1) / (n + 2)$.\n", "\n", "\n", " \n", " \n", "\n", "
What we know is little, and what we are ignorant of is immense.
I. J. Good (1916 - 2009)             Alan Turing (1812 - 1954)\n", "\n", "So, how many one-count words are there in COUNTS? (There aren't any in COUNTS1.) And what are the word lengths of them? Let's find out:\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "singletons = (w for w in COUNTS if COUNTS[w] == 1)\n", "\n", "lengths = map(len, singletons)\n", "\n", "Counter(lengths).most_common()" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 225, "text": [ "[(7, 1357),\n", " (8, 1356),\n", " (9, 1176),\n", " (6, 1113),\n", " (10, 938),\n", " (5, 747),\n", " (11, 627),\n", " (12, 398),\n", " (4, 367),\n", " (13, 215),\n", " (3, 161),\n", " (14, 112),\n", " (2, 51),\n", " (15, 37),\n", " (16, 10),\n", " (17, 7)]" ] } ], "prompt_number": 225 }, { "cell_type": "code", "collapsed": false, "input": [ "1357 / sum(COUNTS.values())" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 213, "text": [ "0.0012278198461651215" ] } ], "prompt_number": 213 }, { "cell_type": "code", "collapsed": false, "input": [ "hist(lengths, bins=len(set(lengths)));" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "display_data", "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAG+RJREFUeJzt3X9MFGfiP/D3bihorouHemIT3GKV7g9/AQpLNchq/EGT\no3AagzZeG8HE485DLdd4UROhyVeDaCyYshLv1qZtrNc0aWq1iMLdqOTOXajN9Sr4Aw8PSE5RaGUR\nqBaf7x98uqeCyC4jM/q8X8kmMDvz7Htg983w7OyuQQghQERE0jBqHYCIiEYWi5+ISDIsfiIiybD4\niYgkw+InIpIMi5+ISDKDFn9WVhYiIyMxY8aMftft2bMHRqMR7e3t/mUlJSWIiYmB3W5HdXW1f3l9\nfT3i4+Px0ksvYevWrSrGJyKiQA1a/GvWrMHx48f7LW9ubsbJkyfx4osv+pe1traitLQUVVVVcLlc\nyM3N9V+Xl5eHzZs3o6amBqdOnUJtba2Ku0BERIEYtPiTk5MRERHRb/lbb72FXbt2PbDM4/EgNTUV\nZrMZKSkpEEKgs7MTAHDx4kVkZmZi3LhxWLZsGTwej4q7QEREgQh4jv/zzz9HVFQUZs6c+cByr9cL\nm83m/95iscDj8aChoQETJkzwL7fb7Th79uwwIhMR0XCEBLJyV1cXduzYgZMnT/qX/fSODwO984PB\nYOi3jO8QQUSkrYCK/8qVK7h69SpmzZoFAGhpacHs2bPh8XjgcDhQWVnpX/fChQtISEiAyWTC9evX\n/cvr6uqQlJQ04PhTp07FlStXgtkPIiJpTZkyBQ0NDUPfQDxGY2OjmD59+oDXRUdHi7a2NiGEENeu\nXRMWi0X85z//EX/7299EXFycf71XX31VfPzxx+LGjRti3rx5oqamZsDxhhBHF7Zv3651hCF5GnI+\nDRmFYE61Mae6Au3OQef4V61ahblz5+LSpUuYNGkSDh48+MD190/lREZGIicnBwsXLsRvf/tbFBcX\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jPf/LO83efJkXZzVM1DOH3/8Uaxbt05YrVaR\nkZEhvF6v1jH7/c7dbrf49ttvxcqVK8XMmTPF66+/Lurr6x87Dl/ARUQkGV1M9RAR0chh8RMRSYbF\nT0QkGRY/EZFkWPxERJJh8RMRSYbFT0QkGRY/EZFk/j/40bg2F6Di4wAAAABJRU5ErkJggg==\n", "text": [ "" ] } ], "prompt_number": 229 }, { "cell_type": "code", "collapsed": false, "input": [ "def pdist_good_turing_hack(counter, onecounter, base=1/26., prior=1e-8):\n", " \"\"\"The probability of word, given evidence from the counter.\n", " For unknown words, look at the one-counts from onecounter, based on length.\n", " This gets ideas from Good-Turing, but doesn't implement all of it.\n", " prior is an additional factor to make unknowns less likely.\n", " base is how much we attenuate probability for each letter beyond longest.\"\"\"\n", " N = sum(counter.values())\n", " N2 = sum(onecounter.values())\n", " lengths = map(len, [w for w in onecounter if onecounter[w] == 1])\n", " ones = Counter(lengths)\n", " longest = max(ones)\n", " return (lambda word: \n", " counter[word] / N if (word in counter) \n", " else prior * (ones[len(word)] / N2 or \n", " ones[longest] / N2 * base ** (len(word)-longest)))\n", "\n", "# Redefine P1w\n", "P1w = pdist_good_turing_hack(COUNTS1, COUNTS)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 230 }, { "cell_type": "code", "collapsed": false, "input": [ "segment.cache.clear()\n", "segment('thisisatestofsegmentationofaverylongsequenceofwords')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 231, "text": [ "['this',\n", " 'is',\n", " 'a',\n", " 'test',\n", " 'of',\n", " 'segmentation',\n", " 'of',\n", " 'a',\n", " 'very',\n", " 'long',\n", " 'sequence',\n", " 'of',\n", " 'words']" ] } ], "prompt_number": 231 }, { "cell_type": "markdown", "metadata": {}, "source": [ "That was somewhat unsatisfactory. We really had to crank up the prior, specifically because the process of running segment generates so many non-word candidates (and also because there will be fewer unknowns with respect to the billion-word WORDS1 than with respect to the million-word WORDS). It would be better to separate out the prior from the word distribution, so that the same distribution could be used for multiple tasks, not just for this one.\n", "\n", "Now let's think for a short while about smoothing **bigram** counts. Specifically, what if we haven't seen a bigram sequence, but we've seen both words individually? For example, to evaluate P(\"Greenland\") in the phrase \"turn left at Greenland\", we might have three pieces of evidence:\n", "\n", " P(\"Greenland\")\n", " P(\"Greenland\" | \"at\")\n", " P(\"Greenland\" | \"left\", \"at\")\n", " \n", "Presumably, the first would have a relatively large count, and thus large reliability, while the second and third would have decreasing counts and reliability. With *interpolation smoothing* we combine all three pieces of evidence, with a linear combination:\n", " \n", "$P(w_3 \\mid w_1w_2) = c_1 P(w_3) + c_2 P(w_3 \\mid w_2) + c_3 P(w_3 \\mid w_1w_2)$\n", "\n", "How do we choose $c_1, c_2, c_3$? By experiment: train on training data, maximize $c$ values on development data, then evaluate on test data.\n", " \n", "However, when we do this, we are saying, with probability $c_1$, that a word can appear anywhere, regardless of previous words. But some words are more free to do that than other words. Consider two words with similar probability:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print P1w('francisco')\n", "print P1w('individuals')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "7.73314623661e-05\n", "7.72494966889e-05\n" ] } ], "prompt_number": 232 }, { "cell_type": "markdown", "metadata": {}, "source": [ "They have similar unigram probabilities but differ in their freedom to be the second word of a bigram:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print [bigram for bigram in COUNTS2 if bigram.endswith('francisco')]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['San francisco', 'san francisco']\n" ] } ], "prompt_number": 234 }, { "cell_type": "code", "collapsed": false, "input": [ "print [bigram for bigram in COUNTS2 if bigram.endswith('individuals')]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['are individuals', 'other individuals', 'on individuals', 'infected individuals', 'in individuals', 'where individuals', 'or individuals', 'which individuals', 'to individuals', 'both individuals', 'help individuals', 'more individuals', 'interested individuals', 'from individuals', ' individuals', 'income individuals', 'these individuals', 'about individuals', 'the individuals', 'among individuals', 'some individuals', 'those individuals', 'by individuals', 'minded individuals', 'These individuals', 'qualified individuals', 'certain individuals', 'different individuals', 'For individuals', 'few individuals', 'and individuals', 'two individuals', 'for individuals', 'between individuals', 'affected individuals', 'healthy individuals', 'private individuals', 'with individuals', 'following individuals', 'as individuals', 'such individuals', 'that individuals', 'all individuals', 'of individuals', 'many individuals']\n" ] } ], "prompt_number": 235 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Intuitively, words that appear in many bigrams before are more likely to appear in a new, previously unseen bigram. In *Kneser-Ney* smoothing (Reinhard Kneser, Hermann Ney) we multiply the bigram counts by this ratio. But I won't implement that here, because The Count never covered it.\n", "\n", "(10) One More Task: Secret Codes\n", "===\n", "\n", "Let's tackle one more task: decoding secret codes. We'll start with the simplest of codes, a rotation cipher, sometimes called a shift cipher or a Caesar cipher (because this was state-of-the-art crypotgraphy in 100 BC). First, a method to encode:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def rot(msg, n=13): \n", " \"Encode a message with a rotation (Caesar) cipher.\" \n", " return encode(msg, alphabet[n:]+alphabet[:n])\n", "\n", "def encode(msg, key): \n", " \"Encode a message with a substitution cipher.\" \n", " table = string.maketrans(upperlower(alphabet), upperlower(key))\n", " return msg.translate(table) \n", "\n", "def upperlower(text): return text.upper() + text.lower() " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 236 }, { "cell_type": "code", "collapsed": false, "input": [ "rot('This is a secret message.', 1)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 237, "text": [ "'Uijt jt b tfdsfu nfttbhf.'" ] } ], "prompt_number": 237 }, { "cell_type": "code", "collapsed": false, "input": [ "rot('This is a secret message.')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 238, "text": [ "'Guvf vf n frperg zrffntr.'" ] } ], "prompt_number": 238 }, { "cell_type": "code", "collapsed": false, "input": [ "rot(rot('This is a secret message.'))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 239, "text": [ "'This is a secret message.'" ] } ], "prompt_number": 239 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now decoding is easy: try all 26 candidates, and find the one with the maximum Pwords:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def decode_rot(secret):\n", " \"Decode a secret message that has been encoded with a rotation cipher.\"\n", " candidates = [rot(secret, i) for i in range(len(alphabet))]\n", " return max(candidates, key=lambda msg: Pwords(tokens(msg)))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 240 }, { "cell_type": "code", "collapsed": false, "input": [ "msg = 'Who knows the answer?'\n", "secret = rot(msg, 17)\n", "\n", "print(secret)\n", "print(decode_rot(secret))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "nyfbefnjkyvrejnvi\n", "['who', 'knows', 'the', 'answer']\n" ] } ], "prompt_number": 249 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's make it a tiny bit harder. When the secret message contains separate words, it is too easy to decode by guessing that the one-letter words are most likely \"I\" or \"a\". So what if the encode routine mushed all the letters together:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def encode(msg, key): \n", " \"Encode a message with a substitution cipher; remove non-letters.\" \n", " msg = cat(tokens(msg)) ## Change here\n", " table = string.maketrans(upperlower(alphabet), upperlower(key))\n", " return msg.translate(table) " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 244 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can decode by segmenting. We change candidates to be a list of segmentations, and still choose the candidate with the best Pwords: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def decode_rot(secret):\n", " \"\"\"Decode a secret message that has been encoded with a rotation cipher,\n", " and which has had all the non-letters squeezed out.\"\"\"\n", " candidates = [segment(rot(secret, i)) for i in range(len(alphabet))]\n", " return max(candidates, key=lambda msg: Pwords(msg))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 245 }, { "cell_type": "code", "collapsed": false, "input": [ "msg = 'Who knows the answer this time? Anyone? Bueller?'\n", "secret = rot(msg, 19)\n", "\n", "print(secret)\n", "print(decode_rot(secret))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "pahdghplmaxtglpxkmablmbfxtgrhgxunxeexk\n", "['who', 'knows', 'the', 'answer', 'this', 'time', 'anyone', 'bueller']" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 247 }, { "cell_type": "code", "collapsed": false, "input": [ "candidates = [segment(rot(secret, i)) for i in range(len(alphabet))]\n", "\n", "for c in candidates:\n", " print c, Pwords(c)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['pahdghplmaxtglpxkma', 'blmbfxtgrhgxunxeexk'] 8.7783378348e-33\n", "['qbiehiqmnbyuhmqylnb', 'cmncgyuhsihyvoyffyl'] 8.7783378348e-33\n", "['rcjfijrnoczvinrzmoc', 'dnodhzvitjizwpzggzm'] 8.7783378348e-33\n", "['sdkgjksopdawjosan', 'pdeopeiawjukjaxqahh', 'an'] 1.53192669415e-32\n", "['tel', 'hkltpqebxkptboqef', 'pqfjbxkvlkbyrbiibo'] 1.59574951877e-32\n", "['ufmilmuqrfcylqucprf', 'gqrgkcylwmlczscjjcp'] 8.7783378348e-33\n", "['vgnjmnvrsgdzmrvdqsg', 'hrshldzmxnmdatdkkdq'] 8.7783378348e-33\n", "['who', 'knows', 'the', 'answer', 'this', 'time', 'anyone', 'bueller'] 7.18422540159e-29\n", "['xiplopxtuifbotxfsui', 'jtujnfbozpofcvfmmfs'] 8.7783378348e-33\n", "['yjqmpqyuvjgcpuygtvj', 'kuvkogcpaqpgdwgnngt'] 8.7783378348e-33\n", "['zkrnqrzvwkhdqvzhuwk', 'lvwlphdqbrqhexhoohu'] 8.7783378348e-33\n", "['also', 'rsawxlierwaivxlmw', 'xmqiercsrifyippiv'] 4.20728492071e-30\n", "['bmtpstbxymjfsxbjwym', 'nxynrjfsdtsjgzjqqjw'] 8.7783378348e-33\n", "['cnuqtucyznkgtyckxz', 'no', 'yzoskgteutkhakrrkx'] 9.4554362126e-33\n", "['do', 'vruvdzaolhuzdlyao', 'pzaptlhufvuliblssly'] 9.5930573844e-33\n", "['epwsvweabpmivaemzbp', 'qabqumivgwvmjcmttmz'] 8.7783378348e-33\n", "['fqxtwxfbcqnjwbfnacq', 'rbcrvnjwhxwnkdnuuna'] 8.7783378348e-33\n", "['gryuxygcdrokxcgobdr', 'scdswokxiyxoleovvob'] 8.7783378348e-33\n", "['hszvyzhdesplydhpc', 'est', 'detxplyjzypmfpwwpc'] 1.52450959071e-32\n", "['it', 'awzaieftqmzeiqdft', 'uefuyqmzkazqngqxxqd'] 2.83847421472e-32\n", "['jubxabjfgurnafjregu', 'vfgvzrnalbarohryyre'] 8.7783378348e-33\n", "['kvcybckghvsobgksfhv', 'wghwasobmcbspiszzsf'] 8.7783378348e-33\n", "['lwdzcdlhiwtpchltgiw', 'xhixbtpcndctqjtaatg'] 8.7783378348e-33\n", "['mxeademijxuqdimuhjx', 'yijycuqdoedurkubbuh'] 8.7783378348e-33\n", "['nyfbefnjkyvrejnviky', 'zjkzdvrepfevslvccvi'] 8.7783378348e-33\n", "['ozgcfgoklzwsfkowjlz', 'aklaewsfqgfwtmwddwj'] 8.7783378348e-33\n" ] } ], "prompt_number": 248 }, { "cell_type": "markdown", "metadata": {}, "source": [ "What about a general substitution cipher? The problem is that there are 26! substitution ciphers, and we can't enumerate all of them. We would need to search through this space. Initially make some guess at a substitution, then swap two letters; if that looks better keep going, if not try something else. This approach solves most substitution cipher problems, although it can take a few minutes on a message of length 100 words or so.\n", "\n", "(\u221e and beyond) Where To Go Next\n", "===\n", "\n", "What to do next? Here are some options:\n", " \n", "- **Spelling correction**: Use bigram or trigram context; make a model of spelling errors/edit distance; go beyond edit distance 2; make it more efficient\n", "- **Evaluation**: Make a serious test suite; search for best parameters (e.g. $c_1, c_2, c_3$)\n", "- **Smoothing**: Implement Kneser-Ney and/or Interpolation; do letter *n*-gram-based smoothing\n", "- **Secret Codes**: Implement a search over substitution ciphers\n", "- **Classification**: Given a corpus of texts, each with a classification label, write a classifier that will take a new text and return a label. Examples: spam/no-spam; favorable/unfavorable; what author am I most like; reading level.\n", "- **Clustering**: Group data by similarity. Find synonyms/related words.\n", "- **Parsing**: Representing nested structures rather than linear sequences of words. relations between parts of the structure. Implicit missing bits. Inducing a grammar.\n", "- **Meaning**: What semantic relations are meant by the syntactic relations?\n", "- **Translation**: Using examples to transform one language into another.\n", "- **Question Answering**: Using examples to transfer a question into an answer, either by retrieving a passage, or by synthesizing one.\n", "- **Speech**: Dealing with analog audio signals rather than discrete sequences of characters." ] } ], "metadata": {} } ] }