Guide to AI and Data Courses · Lecture Notes

Chapter 6: Natural Language Processing and Text Mining

An online store receives thousands of product reviews a day, and the negative ones must reach customer service at once. Reading them one by one is impossible, and to a computer a review is only a string of characters. Natural language processing teaches how to turn that string into numbers first, and then to reason about the numbers with probability. These notes introduce the course and work through its three core ideas with small examples you can compute by hand: turning text into vectors, predicting the next word, and classifying text.

Learning outcomes

Quantifying text
Split a text into tokens; compute a bag-of-words and TF-IDF vector by hand and find the cosine similarity between two documents.
Language model
Estimate bigram probabilities by counting a corpus, and compute the probability and perplexity of a sentence.
Smoothing
Explain why unseen n-grams get zero probability and apply add-one smoothing.
Text classification
Classify a short text with naive Bayes; state the limits of the bag-of-words assumption.
Place of the course
State what separates natural language processing from speech recognition, information retrieval, data mining and generative models.

6.1What question does the course ask?

How does a computer analyze, understand and generate human language?

Natural language processing studies how computers analyze, understand and generate human language; text mining extracts information and patterns from large collections of text. At the heart of the course are text representation, which turns text into numbers, and language models that predict the next word.

The examples in machine learning are mostly numbers: the floor area of a house, a patient's blood pressure. Language is not numbers. "The film was very good" is not a measurement but a sequence of symbols of varying length; the vocabulary grows without bound, order changes meaning ("Ann saw Bob" and "Bob saw Ann" say different things with the same words), and the same thing can be written in countless ways. The question of the course is therefore twofold: how do we turn text into numbers a machine can process, and which properties of language can we capture with those numbers?

The course answers in three layers. The first is text preprocessing: cutting the text into pieces and bringing words to a normal form. The second is representation: turning the pieces into numbers as word counts, TF-IDF weights or embedding vectors. The third is modeling: building a language model, a classifier or a transformer on top of those numbers. The three core sections below work through the classic, hand-traceable forms of these layers; transformers are the same ideas at a much larger scale.

6.1.1Why is Turkish a topic of its own?

In English a word is mostly delimited by spaces and takes few forms (book, books). Turkish is agglutinative: from the root kitap ("book") hundreds of forms such as kitaplarımızdan ("from our books") are derived, and in a word count each of them looks like a separate "word". For Turkish, tokenization and morphological analysis are therefore separate steps to take before counting. The Turkish examples in the course keep reminding us of this difference.

6.1.2At a glance

CriterionNatural Language Processing and Text Mining
Approachlinguistics, statistics and deep learning
Inputtext
Outputlabel, translation, summary, answer
Success measureaccuracy, BLEU, human evaluation
Math loadmedium
Data needslarge text corpora

6.2A short history

YearMilestone
1954Georgetown-IBM experiment: more than sixty Russian sentences are translated into English automatically.
1966Weizenbaum's ELIZA imitates a therapist with simple pattern matching.
1990sStatistical methods replace rule-based systems; IBM's translation models lead the way.
2013Mikolov et al.'s word2vec embeds words as vectors that reflect meaning.
2017The transformer architecture is introduced, followed by pretrained models such as BERT and GPT.
2022Large language models reach a mass audience through chat interfaces.

6.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
TokenizationSplitting text into word or subword units.
MorphologyRoot and suffix analysis; critical in agglutinative languages like Turkish.
Bag of wordsRepresenting text by word counts, ignoring order.
TF-IDFHigh weight for words frequent in a document but rare in the corpus.
Word embeddingsWords with similar meanings lie close in vector space.
Language modelA model that predicts the probability of the next word.
Named entity recognitionFinding names of people, places and organizations in text.
Topic modelingFinding hidden topics in documents with methods such as LDA.

6.4Turning text into numbers: tokenization and TF-IDF

The first job is to split the text into tokens. Splitting on spaces is not enough: punctuation sticks to words, a token like "Ankara'da" carries a root and a suffix together, and upper and lower case split the same word in two. So tokenization is followed by normalization: lowercasing, stripping punctuation and, if needed, stemming. In Turkish, splitting words into root and suffixes (morphology) is an extra step.

WordAnalysisMeaning
evlerimizdenev + ler + imiz + denhouse, plural, "our", ablative (from)
kitaplarımızdankitap + lar + ımız + danbook, plural, "our", ablative (from)
gidemedimgit + eme + di + mgo, inability-negation, past, "I"

The simplest way to turn text into a vector is the bag of words: for every word in a vocabulary we write how many times it occurs in the document and ignore the order. But raw counts have a flaw: words that occur everywhere, like "film" and "very", get large numbers, while the words that actually tell documents apart are rarer. TF-IDF corrects this.

Definition 6.1 (TF-IDF)

tf-idf(t, d) = tf(t, d) × idf(t), where tf(t, d) is the count of term t in document d, idf(t) = log10(N / df(t)), N is the number of documents and df(t) is the number of documents containing the term. (The base of the logarithm and the smoothing variants differ between books; the ordering of the results stays the same.)

Example 6.1: TF-IDF and cosine in a three-document corpus

Corpus: D1 = "film very good", D2 = "film very bad", D3 = "good good music". Number of documents N = 3.

  1. Document frequency. film, very, good: df = 2; bad, music: df = 1.
  2. IDF. log10(3/2) ≈ 0.176 (film, very, good); log10(3/1) ≈ 0.477 (bad, music).
  3. D1 vector. Each term occurs once: film 0.176; very 0.176; good 0.176; length √3 · 0.176 ≈ 0.305.
  4. D2 vector. film 0.176; very 0.176; bad 0.477; length √(0.031 + 0.031 + 0.228) ≈ 0.538.
  5. Cosine similarity. The shared terms are film and very: dot product 0.1762 + 0.1762 ≈ 0.062; cos(D1, D2) = 0.062 / (0.305 · 0.538) ≈ 0.38.
  6. Comparison. With raw counts the cosine of the same two documents is 2 / (√3 · √3) ≈ 0.67. TF-IDF lowers the weight of shared but non-distinctive words, so the similarity drops from 0.67 to 0.38. D2 and D3 share no word at all: the cosine is 0.

In D3 "good" occurs twice, so its TF-IDF is 2 · 0.176 ≈ 0.352 and that of "music" is 0.477: count and rarity together set the weight.

Cosine similarity is the cosine of the angle between two vectors; it does not depend on length, so long and short documents are compared fairly. The information retrieval course (Information Retrieval) uses the same vector-space idea for the similarity between a query and a document; embeddings replace count vectors with dense vectors that carry meaning.

Common mistake

Assuming that lowercasing is the same in every language. In many programming languages the default conversion maps I → i; in Turkish the correct rule is I → ı and İ → i. The word "IŞIK" ("light") becomes "işik" under the default conversion and cannot be found in a dictionary. For Turkish text a locale-aware lowercasing or a custom mapping is used.

6.5Language models: n-grams and smoothing

A language model assigns probabilities to word sequences. After "the weather today is very" a word like "nice" is far more likely than "plate"; a language model turns this intuition into a number. The probability of a sequence is split by the chain rule into a product of conditional probabilities: P(w1…wn) = Π P(wi | w1…wi−1). Counting the whole history is impossible, so an n-gram model looks only at the last few words. A bigram model uses P(wi | wi−1).

Definition 6.2 (Bigram probability (maximum likelihood))

P(b | a) = count(a b) / count(a): the share of times that a is followed by b. Sentence-start <s> and sentence-end </s> markers are added.

Example 6.2: Bigram probabilities and perplexity

A three-sentence corpus (Turkish words, glossed in brackets): <s> ben kitap okurum </s> (I read books), <s> ben film izlerim </s> (I watch films), <s> sen kitap okursun </s> (you read books).

  1. Counts. <s> occurs 3 times, "ben" 2 times, "kitap" 2 times, "okurum" once.
  2. Probabilities. P(ben | <s>) = 2/3; P(kitap | ben) = 1/2; P(okurum | kitap) = 1/2; P(</s> | okurum) = 1.
  3. Sentence probability. P("ben kitap okurum") = 2/3 · 1/2 · 1/2 · 1 = 1/6 ≈ 0.167.
  4. Perplexity. Four probabilities were multiplied, so four words (including </s>) were predicted. PP = (1/6)−1/4 = 61/4 ≈ 1.57. At each step the model is on average as unsure as if choosing among about 1.57 options; the smaller, the better.
  5. Unseen bigram. "sen film" is not in the corpus: P(film | sen) = 0/1 = 0. If one factor of the product is zero, the whole sentence gets zero probability, even a plausible one like "sen film okurum".

The remedy for zero probabilities is smoothing. The simplest form is add-one (Laplace) smoothing: 1 is added to every bigram count and the denominator grows by the vocabulary size V: P(b | a) = (count(a b) + 1) / (count(a) + V).

Example 6.3: Add-one smoothing

In the same corpus the vocabulary is V = 8 (ben, kitap, okurum, film, izlerim, sen, okursun, </s>).

  1. Seen bigram. P(kitap | ben) = (1 + 1) / (2 + 8) = 0.2 (0.5 before smoothing).
  2. Unseen bigram. P(film | sen) = (0 + 1) / (1 + 8) ≈ 0.111; no longer zero.
  3. New sentence. For "sen film okurum": P(sen | <s>) = (1+1)/(3+8) ≈ 0.182; P(film | sen) ≈ 0.111; P(okurum | film) = 1/9 ≈ 0.111; P(</s> | okurum) = (1+1)/(1+8) ≈ 0.222. The product is ≈ 0.0005, the perplexity ≈ 6.69.
  4. The price. The same smoothing also changes the probability of a seen sentence: for "ben kitap okurum" it falls from 1/6 to about 0.0024 and the perplexity rises from 1.57 to 4.51. Setting aside mass for unseen events takes it from the seen ones.

With a tiny corpus the price is large; with a real corpus V is large, counts are high and the effect is much milder. In practice finer smoothing methods such as Kneser-Ney are used.

Transformers and large language models answer the same question: what is the probability of the next word? The differences are that the history is not limited to the last word or two, and that the probabilities are computed by a neural network instead of by counting (Deep Learning). The quality of a language model is still measured by perplexity.

Common mistake

Comparing perplexity between models with different vocabularies, or measuring a model on the sentences it was trained on. A model with a small vocabulary looks easy; the value on training sentences does not reflect real performance. Perplexity is measured on a held-out test corpus with the same vocabulary.

6.6Text classification: naive Bayes

Text classification assigns a class to a document: positive/negative, spam/normal, sports/economy. A classic and surprisingly strong method is naive Bayes. With Bayes' rule, for a document d we write P(c | d) ∝ P(c) · P(d | c); the "naive" assumption is that the words of the document are independent of one another given the class: P(d | c) = Π P(wi | c). This is the bag-of-words idea restated in terms of probability. (For Bayes' rule and conditional probability see Probability and Statistics.)

Definition 6.3 (Multinomial naive Bayes with add-one smoothing)

P(c) = number of documents in class c / total number of documents; P(w | c) = (count of w in class c + 1) / (total number of words in class c + V). The chosen class is the one that maximizes P(c) · Π P(wi | c).

Example 6.4: A sentiment classifier on three-word reviews

Training corpus (five reviews): positive: "very good film", "good good"; negative: "bad film", "very bad", "bad bad film". Vocabulary V = 4 (very, good, film, bad). Test review: "good film".

  1. Priors. P(positive) = 2/5, P(negative) = 3/5.
  2. Word counts. The positive class has 5 words in total: good 3, very 1, film 1. The negative class has 7 words in total: bad 4, film 2, very 1.
  3. Positive likelihoods. P(good | positive) = (3+1)/(5+4) = 4/9; P(film | positive) = (1+1)/9 = 2/9.
  4. Negative likelihoods. P(good | negative) = (0+1)/(7+4) = 1/11; P(film | negative) = (2+1)/11 = 3/11.
  5. Scores. Positive: 2/5 · 4/9 · 2/9 ≈ 0.0395. Negative: 3/5 · 1/11 · 3/11 ≈ 0.0149.
  6. Decision. Normalizing gives P(positive | d) = 0.0395 / (0.0395 + 0.0149) ≈ 0.73. Although the negative class has the larger prior, the positive word "good" tips the choice to positive.

For the review "good bad" the scores are 0.0198 (positive) and 0.0248 (negative); the probabilities are about 0.44 and 0.56: on a mixed review the model is undecided and picks negative by a small margin.

Smoothing is needed here too: had we never seen "good" in the negative class, P(good | negative) = 0 and every review containing "good", whatever else it said, would get zero score for the negative class. In long documents many small probabilities are multiplied, so to avoid underflow the sum of logarithms is taken instead of the product. Evaluation uses accuracy, precision, recall and F1 (Machine Learning).

Common mistake

Forgetting that a bag of words sees neither order nor negation. In the review "the film is not good" the model counts "good" as positive evidence, and "not" alone is weak evidence. Remedies are to mark negation ("good_NOT"), to add bigram features, or to move to transformer models that see the context.

6.7How is the course taught?

6.7.1A typical workflow

CollecttextcorpusPreprocesstokenizing,stemmingRepresentTF-IDF,embeddingsModelclassifier,transformerEvaluateF1, BLEU
Figure 6.1: A typical workflow in Natural Language Processing and Text Mining

An online store collects product reviews, tokenizes the text and analyzes suffixes, turns the reviews into vectors with a pretrained transformer, trains a positive/negative sentiment classifier and measures it with the F1 score. The result shows which topics the complaints cluster around.

6.7.2Topics over the semester

  1. Regular expressions, tokenization, normalization
  2. Morphology: stemming and morphological analysis
  3. N-gram language models and smoothing
  4. Text classification: naive Bayes, logistic regression
  5. Vector semantics: TF-IDF and word2vec
  6. Part-of-speech tagging and hidden Markov models
  7. Named entity recognition and sequence labeling (CRF)
  8. Syntactic parsing: dependency trees
  9. Language modeling with recurrent networks
  10. Transformers, BERT and pretraining
  11. Machine translation and evaluation with BLEU
  12. Topic modeling (LDA) and information extraction

This is a typical semester; the order and coverage vary between universities.

6.7.3Skills you will gain

  • text processing with spaCy and NLTK
  • cleaning text with regular expressions
  • Turkish morphology with Zemberek
  • word embeddings with Gensim
  • fine-tuning a Hugging Face model
  • evaluating with F1 and BLEU

6.7.4Try it yourself

The Try It: Is the Customer Review Positive? slide in the presentation lets you solve a typical problem of this course yourself: An online store gets thousands of reviews a day; negative ones should go straight to customer service. Pick a sample review or write your own; the model scores the words one by one.

6.8Are you ready for this course?

6.8.1Prerequisites

CourseWhy it is needed
Artificial Intelligencelanguage understanding and generation
Programmingstring handling, file reading and regular expressions in Python
Data Structuresdictionaries, hash tables and tries: for storing a vocabulary

6.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you process strings in Python and search text with a regex?An intro programming course, then a short regex tutorial
Can you count word frequencies using a dictionary (hash table)?Hash tables from a data structures course
Can you explain conditional probability and Bayes' rule?Probability and Statistics
Can you evaluate a classifier with precision, recall and F1?Machine Learning

6.9Neighboring courses

Artificial IntelligenceDeep LearningIR & RecommendersData MiningSpeech and AudioGraphical ModelsGenerative ModelsNLP
subfieldbuilds onshares methodsapplication
Figure 6.2: Neighbors of Natural Language Processing and Text Mining and the kind of relation

6.9.1Where it overlaps

RelationCourseShared ground
subfieldThis course is a subfield of Artificial Intelligencelanguage understanding and generation
shares methodsShares methods with Deep Learningword embeddings, transformer architecture
shares methodsShares methods with Probabilistic Graphical Modelshidden Markov model, conditional random field
shares methodsShares methods with Generative Modelstext generation
shares methodsShares methods with Speech Recognition and Audio Processinglanguage model, speech to text
shares methodsShares methods with Data Miningtext classification, topic modeling
shares methodsShares methods with Information Retrieval and Recommender Systemstext representation, TF-IDF, semantic search

6.9.2Where it differs

  • Speech Recognition and Audio Processing: Speech recognition goes from the sound wave to text; NLP analyzes meaning once the text is available.
  • Information Retrieval and Recommender Systems: Information retrieval fetches the documents most relevant to a query; NLP analyzes and generates the language inside them in detail.
  • Data Mining: Data mining looks for patterns in any kind of data; this course handles the structure specific to language (words, suffixes, sentences).
  • Generative Models: Generative models produce all kinds of samples, including images and audio; NLP also covers understanding and analysis tasks.

6.10In practice

6.10.1Applications

AreaWhat is done
Machine translationAutomatic translation between languages.
Sentiment analysisFinding the attitude in reviews and posts.
Question answeringFinding answers in documents or a knowledge base.
SummarizationMaking a long text short and to the point.
Chat assistantsSystems that talk with users in natural language.
Document classificationSorting news, petitions or emails by topic.

6.10.2Risks and ethics

RiskExplanation
HallucinationLanguage models fluently invent sources that do not exist; in the US, lawyers have filed briefs citing case law a chatbot made up.
Stereotypes in embeddingsEmbeddings produce analogies like "man is to programmer as woman is to homemaker"; translation renders neutral pronouns by stereotype.
Low-resource languagesModels work best in English; on Turkish and languages with little data the same system makes noticeably more errors.
Surveillance through textEmails, messages and posts are personal data under GDPR and similar laws; text mining can also be used to monitor and profile people.

These issues are discussed in depth in Explainable AI and AI Ethics.

6.10.3Tools and datasets

Tools: NLTK, spaCy, Hugging Face Transformers, Gensim, Stanza, Zemberek (Turkish).

Well-known datasets: Penn Treebank, CoNLL-2003, SQuAD, GLUE, IMDb movie reviews, Wikipedia dumps.

6.11Common misconceptions

Common mistake

The model understands text like a human.

Language models learn statistical patterns; fluent text is not always correct or consistent.

Common mistake

Any method built for English works for Turkish.

In agglutinative Turkish one root takes hundreds of forms; tokenization and morphology need separate care.

Common mistake

Large language models ended classic NLP.

TF-IDF, regular expressions and small models are still fast, cheap and enough for most jobs.

Common mistake

Text mining is just counting words.

Counting is the start; extracting entities, relations and topics requires language structure.

6.12Summary

  • Natural language processing first splits text into tokens and normalizes it, then turns it into numbers; in agglutinative Turkish, root-suffix analysis is a separate step.
  • A bag of words records counts, while TF-IDF gives high weight to words frequent in a document but rare in the corpus; documents are compared as vectors by cosine similarity.
  • A language model assigns probabilities to word sequences; a bigram probability is the ratio count(a b) / count(a) and quality is measured by perplexity.
  • Unseen n-grams get zero probability; smoothing such as add-one fixes this, but takes probability mass from seen events.
  • Naive Bayes classifies a document by assuming words are independent given the class; it is fast, but sees neither order nor negation.

6.13Test Yourself

  1. "Kitaplarımızdan" is three words in English ("from our books"). Why does a tokenizer that splits on spaces cause trouble in Turkish text?

    Answer

    In Turkish suffixes attach to the word; "kitaplarımızdan" becomes one token, and "kitap", "kitaplar", "kitaplarımız" count as different words. The vocabulary swells, each form stays rare and the statistics of one root are scattered. Morphological analysis or subword tokenization solves this.

  2. In a corpus of 100 documents the word "model" occurs in 10 documents and the word "and" in 100. If each occurs 3 times in a document, what are their TF-IDF values (base-10 logarithm)?

    Answer

    idf(model) = log10(100/10) = 1, TF-IDF = 3 · 1 = 3. idf(and) = log10(100/100) = 0, TF-IDF = 3 · 0 = 0. A word that occurs in every document does not distinguish anything, so its weight is zero.

  3. In a corpus the word "ben" occurs 4 times; it is followed by "okurum" 3 times and by "giderim" once. The vocabulary is V = 10. What are P(okurum | ben) and P(yüzerim | ben) by maximum likelihood and by add-one smoothing?

    Answer

    Maximum likelihood: P(okurum | ben) = 3/4 = 0.75; P(yüzerim | ben) = 0/4 = 0. Add-one: P(okurum | ben) = (3+1)/(4+10) = 4/14 ≈ 0.286; P(yüzerim | ben) = (0+1)/14 ≈ 0.071. The unseen bigram is no longer zero, and the probability of the seen one went down.

  4. A language model gives a 4-word test sentence probability 0.0016. What is its perplexity? What probability would it have had if every word had received the same probability?

    Answer

    PP = (0.0016)−1/4. Since 0.24 = 0.0016, PP = 1/0.2 = 5. With the same probability for every word it would be 0.2 (that is, 1/5) per word: the model is as unsure as if choosing among 5 equally likely options at each step.

  5. How does the naive Bayes classifier trained on the corpus of this chapter classify the one-word review "bad"? Compute the positive and negative probabilities.

    Answer

    Positive score: P(positive) · P(bad | positive) = 2/5 · (0+1)/9 ≈ 0.0444. Negative score: 3/5 · (4+1)/11 ≈ 0.2727. Normalizing, P(negative | d) = 0.2727 / (0.0444 + 0.2727) ≈ 0.86 and P(positive | d) ≈ 0.14: the review is classified as negative.

  6. A call center wants to extract customer complaints from recorded calls. Which courses handle turning the audio into text, and finding the complaint topic in the text?

    Answer

    Turning audio into text is the job of speech recognition (Speech and Audio Processing). Finding the complaint topic in the resulting text (classification, topic modeling, entity recognition) is the job of natural language processing and text mining. The two courses work in sequence: audio becomes text first, then the language is analyzed.

6.14After this course

After NLP you can move to spoken language with speech recognition, to semantic search with information retrieval, or to the inner workings of large language models with generative models. The Explainable AI and AI Ethics course covers the bias and reliability problems of language models.

Related careers: NLP engineer, Computational linguist, Data scientist, Search and recommendation engineer, Researcher.

6.15Further reading

  • D. Jurafsky and J. H. Martin, Speech and Language Processing (3rd ed., online draft): covers n-gram language models, smoothing, text classification with naive Bayes and vector semantics at textbook level.
  • J. Eisenstein, Introduction to Natural Language Processing (2019): a modern view that runs from bags of words to neural networks.
  • S. Bird, E. Klein and E. Loper, Natural Language Processing with Python (2009): shows tokenization, classification and language processing with NLTK code.

6.16References

  1. Jurafsky and Martin, Speech and Language Processing, 2nd ed., Prentice Hall, 2009.
  2. Manning and Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999.
  3. Bird, Klein and Loper, Natural Language Processing with Python, O'Reilly, 2009.
  4. Eisenstein, Introduction to Natural Language Processing, MIT Press, 2019.
  5. Vaswani et al., "Attention Is All You Need", Advances in Neural Information Processing Systems 30, 2017.

Related pages: Slides · Slides (PDF) · Course page