{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## April 15th\n", "\n", "Natural Language Processing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# TEXT\n", "\n", "This notebook serves as supporting material for topics covered in **Chapter 22 - Natural Language Processing** from the book *Artificial Intelligence: A Modern Approach*. This notebook uses implementations from [text.py](https://github.com/aimacode/aima-python/blob/master/text.py)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from text import *\n", "from utils import open_data\n", "from notebook import psource" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTENTS\n", "\n", "* Text Models\n", "* Viterbi Text Segmentation\n", "* Information Retrieval\n", "* Information Extraction\n", "* Decoders" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## TEXT MODELS\n", "\n", "Before we start analyzing text processing algorithms, we will need to build some language models. Those models serve as a look-up table for character or word probabilities (depending on the type of model). These models can give us the probabilities of words or character sequences appearing in text. Take as example \"the\". Text models can give us the probability of \"the\", *P(\"the\")*, either as a word or as a sequence of characters (\"t\" followed by \"h\" followed by \"e\"). The first representation is called \"word model\" and deals with words as distinct objects, while the second is a \"character model\" and deals with sequences of characters as objects. Note that we can specify the number of words or the length of the char sequences to better suit our needs. So, given that number of words equals 2, we have probabilities in the form *P(word1, word2)*. For example, *P(\"of\", \"the\")*. For char models, we do the same but for chars.\n", "\n", "It is also useful to store the conditional probabilities of words given preceding words. That means, given we found the words \"of\" and \"the\", what is the chance the next word will be \"world\"? More formally, *P(\"world\"|\"of\", \"the\")*. Generalizing, *P(Wi|Wi-1, Wi-2, ... , Wi-n)*.\n", "\n", "We call the word model *N-Gram Word Model* (from the Greek \"gram\", the root of \"write\", or the word for \"letter\") and the char model *N-Gram Character Model*. In the special case where *N* is 1, we call the models *Unigram Word Model* and *Unigram Character Model* respectively.\n", "\n", "In the `text` module we implement the two models (both their unigram and n-gram variants) by inheriting from the `CountingProbDist` from `learning.py`. Note that `CountingProbDist` does not return the actual probability of each object, but the number of times it appears in our test data.\n", "\n", "For word models we have `UnigramWordModel` and `NgramWordModel`. We supply them with a text file and they show the frequency of the different words. We have `UnigramCharModel` and `NgramCharModel` for the character models.\n", "\n", "Execute the cells below to take a look at the code." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "
\n", "class UnigramWordModel(CountingProbDist):\n",
"\n",
" """This is a discrete probability distribution over words, so you\n",
" can add, sample, or get P[word], just like with CountingProbDist. You can\n",
" also generate a random text, n words long, with P.samples(n)."""\n",
"\n",
" def __init__(self, observations, default=0):\n",
" # Call CountingProbDist constructor,\n",
" # passing the observations and default parameters.\n",
" super(UnigramWordModel, self).__init__(observations, default)\n",
"\n",
" def samples(self, n):\n",
" """Return a string of n words, random according to the model."""\n",
" return ' '.join(self.sample() for i in range(n))\n",
"\n",
"\n",
"class NgramWordModel(CountingProbDist):\n",
"\n",
" """This is a discrete probability distribution over n-tuples of words.\n",
" You can add, sample or get P[(word1, ..., wordn)]. The method P.samples(n)\n",
" builds up an n-word sequence; P.add_cond_prob and P.add_sequence add data."""\n",
"\n",
" def __init__(self, n, observation_sequence=None, default=0):\n",
" # In addition to the dictionary of n-tuples, cond_prob is a\n",
" # mapping from (w1, ..., wn-1) to P(wn | w1, ... wn-1)\n",
" CountingProbDist.__init__(self, default=default)\n",
" self.n = n\n",
" self.cond_prob = defaultdict()\n",
" self.add_sequence(observation_sequence or [])\n",
"\n",
" # __getitem__, top, sample inherited from CountingProbDist\n",
" # Note that they deal with tuples, not strings, as inputs\n",
"\n",
" def add_cond_prob(self, ngram):\n",
" """Build the conditional probabilities P(wn | (w1, ..., wn-1)"""\n",
" if ngram[:-1] not in self.cond_prob:\n",
" self.cond_prob[ngram[:-1]] = CountingProbDist()\n",
" self.cond_prob[ngram[:-1]].add(ngram[-1])\n",
"\n",
" def add_sequence(self, words):\n",
" """Add each tuple words[i:i+n], using a sliding window."""\n",
" n = self.n\n",
"\n",
" for i in range(len(words) - n + 1):\n",
" t = tuple(words[i:i + n])\n",
" self.add(t)\n",
" self.add_cond_prob(t)\n",
"\n",
" def samples(self, nwords):\n",
" """Generate an n-word sentence by picking random samples\n",
" according to the model. At first pick a random n-gram and\n",
" from then on keep picking a character according to\n",
" P(c|wl-1, wl-2, ..., wl-n+1) where wl-1 ... wl-n+1 are the\n",
" last n - 1 words in the generated sentence so far."""\n",
" n = self.n\n",
" output = list(self.sample())\n",
"\n",
" for i in range(n, nwords):\n",
" last = output[-n+1:]\n",
" next_word = self.cond_prob[tuple(last)].sample()\n",
" output.append(next_word)\n",
"\n",
" return ' '.join(output)\n",
"\n",
"\n",
"class UnigramCharModel(NgramCharModel):\n",
" def __init__(self, observation_sequence=None, default=0):\n",
" CountingProbDist.__init__(self, default=default)\n",
" self.n = 1\n",
" self.cond_prob = defaultdict()\n",
" self.add_sequence(observation_sequence or [])\n",
"\n",
" def add_sequence(self, words):\n",
" for word in words:\n",
" for char in word:\n",
" self.add(char)\n",
"\n",
"\n",
"class NgramCharModel(NgramWordModel):\n",
" def add_sequence(self, words):\n",
" """Add an empty space to every word to catch the beginning of words."""\n",
" for word in words:\n",
" super().add_sequence(' ' + word)\n",
"
def words(text, reg=re.compile('[a-z0-9]+')):\n",
" """Return a list of the words in text, ignoring punctuation and\n",
" converting everything to lowercase (to canonicalize).\n",
" >>> words("``EGAD!'' Edgar cried.")\n",
" ['egad', 'edgar', 'cried']\n",
" """\n",
" return reg.findall(text.lower())\n",
"
def viterbi_segment(text, P):\n",
" """Find the best segmentation of the string of characters, given the\n",
" UnigramWordModel P."""\n",
" # best[i] = best probability for text[0:i]\n",
" # words[i] = best word ending at position i\n",
" n = len(text)\n",
" words = [''] + list(text)\n",
" best = [1.0] + [0.0] * n\n",
" # Fill in the vectors best words via dynamic programming\n",
" for i in range(n+1):\n",
" for j in range(0, i):\n",
" w = text[j:i]\n",
" curr_score = P[w] * best[i - len(w)]\n",
" if curr_score >= best[i]:\n",
" best[i] = curr_score\n",
" words[i] = w\n",
" # Now recover the sequence of best words\n",
" sequence = []\n",
" i = len(words) - 1\n",
" while i > 0:\n",
" sequence[0:0] = [words[i]]\n",
" i = i - len(words[i])\n",
" # Return sequence of best words and overall probability\n",
" return sequence, best[-1]\n",
"
class IRSystem:\n",
"\n",
" """A very simple Information Retrieval System, as discussed in Sect. 23.2.\n",
" The constructor s = IRSystem('the a') builds an empty system with two\n",
" stopwords. Next, index several documents with s.index_document(text, url).\n",
" Then ask queries with s.query('query words', n) to retrieve the top n\n",
" matching documents. Queries are literal words from the document,\n",
" except that stopwords are ignored, and there is one special syntax:\n",
" The query "learn: man cat", for example, runs "man cat" and indexes it."""\n",
"\n",
" def __init__(self, stopwords='the a of'):\n",
" """Create an IR System. Optionally specify stopwords."""\n",
" # index is a map of {word: {docid: count}}, where docid is an int,\n",
" # indicating the index into the documents list.\n",
" self.index = defaultdict(lambda: defaultdict(int))\n",
" self.stopwords = set(words(stopwords))\n",
" self.documents = []\n",
"\n",
" def index_collection(self, filenames):\n",
" """Index a whole collection of files."""\n",
" prefix = os.path.dirname(__file__)\n",
" for filename in filenames:\n",
" self.index_document(open(filename).read(),\n",
" os.path.relpath(filename, prefix))\n",
"\n",
" def index_document(self, text, url):\n",
" """Index the text of a document."""\n",
" # For now, use first line for title\n",
" title = text[:text.index('\\n')].strip()\n",
" docwords = words(text)\n",
" docid = len(self.documents)\n",
" self.documents.append(Document(title, url, len(docwords)))\n",
" for word in docwords:\n",
" if word not in self.stopwords:\n",
" self.index[word][docid] += 1\n",
"\n",
" def query(self, query_text, n=10):\n",
" """Return a list of n (score, docid) pairs for the best matches.\n",
" Also handle the special syntax for 'learn: command'."""\n",
" if query_text.startswith("learn:"):\n",
" doctext = os.popen(query_text[len("learn:"):], 'r').read()\n",
" self.index_document(doctext, query_text)\n",
" return []\n",
"\n",
" qwords = [w for w in words(query_text) if w not in self.stopwords]\n",
" shortest = argmin(qwords, key=lambda w: len(self.index[w]))\n",
" docids = self.index[shortest]\n",
" return heapq.nlargest(n, ((self.total_score(qwords, docid), docid) for docid in docids))\n",
"\n",
" def score(self, word, docid):\n",
" """Compute a score for this word on the document with this docid."""\n",
" # There are many options; here we take a very simple approach\n",
" return (log(1 + self.index[word][docid]) /\n",
" log(1 + self.documents[docid].nwords))\n",
"\n",
" def total_score(self, words, docid):\n",
" """Compute the sum of the scores of these words on the document with this docid."""\n",
" return sum(self.score(word, docid) for word in words)\n",
"\n",
" def present(self, results):\n",
" """Present the results as a list."""\n",
" for (score, docid) in results:\n",
" doc = self.documents[docid]\n",
" print(\n",
" ("{:5.2}|{:25} | {}".format(100 * score, doc.url,\n",
" doc.title[:45].expandtabs())))\n",
"\n",
" def present_results(self, query_text, n=10):\n",
" """Get results for the query and present them."""\n",
" self.present(self.query(query_text, n))\n",
"
class UnixConsultant(IRSystem):\n",
"\n",
" """A trivial IR system over a small collection of Unix man pages."""\n",
"\n",
" def __init__(self):\n",
" IRSystem.__init__(self, stopwords="how do i the a of")\n",
"\n",
" import os\n",
" aima_root = os.path.dirname(__file__)\n",
" mandir = os.path.join(aima_root, 'aima-data/MAN/')\n",
" man_files = [mandir + f for f in os.listdir(mandir)\n",
" if f.endswith('.txt')]\n",
"\n",
" self.index_collection(man_files)\n",
"
class ShiftDecoder:\n",
"\n",
" """There are only 26 possible encodings, so we can try all of them,\n",
" and return the one with the highest probability, according to a\n",
" bigram probability distribution."""\n",
"\n",
" def __init__(self, training_text):\n",
" training_text = canonicalize(training_text)\n",
" self.P2 = CountingProbDist(bigrams(training_text), default=1)\n",
"\n",
" def score(self, plaintext):\n",
" """Return a score for text based on how common letters pairs are."""\n",
"\n",
" s = 1.0\n",
" for bi in bigrams(plaintext):\n",
" s = s * self.P2[bi]\n",
"\n",
" return s\n",
"\n",
" def decode(self, ciphertext):\n",
" """Return the shift decoding of text with the best score."""\n",
"\n",
" return argmax(all_shifts(ciphertext), key=lambda shift: self.score(shift))\n",
"
class PermutationDecoder:\n",
"\n",
" """This is a much harder problem than the shift decoder. There are 26!\n",
" permutations, so we can't try them all. Instead we have to search.\n",
" We want to search well, but there are many things to consider:\n",
" Unigram probabilities (E is the most common letter); Bigram probabilities\n",
" (TH is the most common bigram); word probabilities (I and A are the most\n",
" common one-letter words, etc.); etc.\n",
" We could represent a search state as a permutation of the 26 letters,\n",
" and alter the solution through hill climbing. With an initial guess\n",
" based on unigram probabilities, this would probably fare well. However,\n",
" I chose instead to have an incremental representation. A state is\n",
" represented as a letter-to-letter map; for example {'z': 'e'} to\n",
" represent that 'z' will be translated to 'e'."""\n",
"\n",
" def __init__(self, training_text, ciphertext=None):\n",
" self.Pwords = UnigramWordModel(words(training_text))\n",
" self.P1 = UnigramWordModel(training_text) # By letter\n",
" self.P2 = NgramWordModel(2, words(training_text)) # By letter pair\n",
"\n",
" def decode(self, ciphertext):\n",
" """Search for a decoding of the ciphertext."""\n",
" self.ciphertext = canonicalize(ciphertext)\n",
" # reduce domain to speed up search\n",
" self.chardomain = {c for c in self.ciphertext if c != ' '}\n",
" problem = PermutationDecoderProblem(decoder=self)\n",
" solution = search.best_first_graph_search(\n",
" problem, lambda node: self.score(node.state))\n",
"\n",
" solution.state[' '] = ' '\n",
" return translate(self.ciphertext, lambda c: solution.state[c])\n",
"\n",
" def score(self, code):\n",
" """Score is product of word scores, unigram scores, and bigram scores.\n",
" This can get very small, so we use logs and exp."""\n",
"\n",
" # remake code dictionary to contain translation for all characters\n",
" full_code = code.copy()\n",
" full_code.update({x: x for x in self.chardomain if x not in code})\n",
" full_code[' '] = ' '\n",
" text = translate(self.ciphertext, lambda c: full_code[c])\n",
"\n",
" # add small positive value to prevent computing log(0)\n",
" # TODO: Modify the values to make score more accurate\n",
" logP = (sum(log(self.Pwords[word] + 1e-20) for word in words(text)) +\n",
" sum(log(self.P1[c] + 1e-5) for c in text) +\n",
" sum(log(self.P2[b] + 1e-10) for b in bigrams(text)))\n",
" return -exp(logP)\n",
"