Commit f7de5a89 authored by Marco Kuhlmann's avatar Marco Kuhlmann
Browse files

Remove solutions

parent 50db4229
%% Cell type:markdown id: tags:
# Basic text processing
%% Cell type:markdown id: tags:
The purpose of this notebook is to introduce you to some basic concepts and techniques for processing text data.
%% Cell type:markdown id: tags:
## Dataset
%% Cell type:markdown id: tags:
The dataset for this notebook is [WikiText](https://www.salesforce.com/products/einstein/ai-research/the-wikitext-dependency-language-modeling-dataset/), which is based on text extracted from ‘Good’ and ‘Featured’ articles on English Wikipedia. More specifically, we will be using the training portion of the WikiText-2 dataset.
We start by opening the file and store its contents in a list:
%% Cell type:code id: tags:
``` python
with open('wiki.train.tokens', encoding='utf-8') as fp:
wikitext = fp.readlines()
```
%% Cell type:markdown id: tags:
Here is a sample line from the file:
%% Cell type:code id: tags:
``` python
wikitext[1234]
```
%% Cell type:markdown id: tags:
**🤔 Problem 1: A close look at the data**
> Take a close look at this line and compare it with the [original](https://en.wikipedia.org/wiki/The_Feast_of_the_Goat#Critical_reception). You will notice several differences between the two texts. What are your hypotheses as to how these differences come about?
%% Cell type:markdown id: tags:
## Tokenization
%% Cell type:markdown id: tags:
Many tasks in natural language processing rely on first segmenting the raw text into words or word-like units. This task is called **tokenization**.
In English, words are often separated from each other by whitespace, but whitespace is neither necessary nor sufficient to define what constitutes a word. In our example, names such as *Latin America*, *Michael Wood*, and *London Review of Books* could arguably be treated as large words even though they contain spaces, while segments such as *day-to-day* need to be separated into several parts.
In real applications, we would have to tokenize the raw text ourselves, perhaps using some library such as [spaCy](https://spacy.io) or [Stanford CoreNLP](https://stanfordnlp.github.io/CoreNLP/). The WikiText dataset, however, is pre-tokenized, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:
%% Cell type:code id: tags:
``` python
def tokens(lines):
for line in lines:
for token in line.rstrip().split():
yield token
```
%% Cell type:markdown id: tags:
With this, we can count the number of tokens in the dataset:
%% Cell type:code id: tags:
``` python
sum(1 for t in tokens(wikitext))
```
%% Cell type:markdown id: tags:
## Vocabulary
%% Cell type:markdown id: tags:
The term *word* is used ambiguously in natural language processing. It can either refer to a *word token*, a word as it occurs in the running text; or to a *word type*, a unique word. To illustrate the distinction: We are interested in *word tokens* when we want to count the length of a text, and in *word types* when we want to compile a dictionary of all words in the text material.
The set of unique words in a dataset or task is called the **vocabulary**.
%% Cell type:code id: tags:
``` python
vocab = set(tokens(wikitext))
```
%% Cell type:markdown id: tags:
Show the size of the vocabulary:
%% Cell type:code id: tags:
``` python
len(vocab)
```
%% Cell type:markdown id: tags:
**🤔 Problem 2: Missing words**
> When you compare this number to the corresponding number on the [WikiText website](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), you will notice a small difference. Try to find out what causes this difference, and how you can change the code so that you get the same number as on the website.
%% Cell type:code id: tags:solution
``` python
def tokens(lines):
for line in lines:
for token in line.rstrip().split():
yield token
yield '<eos>'
vocab = set(tokens(wikitext))
len(vocab)
```
%% Cell type:markdown id: tags:
For some natural language processing tasks, tokenization is the only thing we need to do in order to compile the vocabulary. For other tasks, we may want to apply additional pre-processing, and/or include only the most frequent words into the vocabulary.
%% Cell type:markdown id: tags:
**🤔 Problem 3: Normalization**
> The term **text normalization** refers to all kinds of pre-processing that we apply to a text in order to bring it into a more standard, convenient form. Two standard normalization techniques are lowercasing and the filtering-out of non-alphabetical tokens. What effect do these techniques have on the size of the vocabulary?
%% Cell type:code id: tags:solution
``` python
def preprocess(tokens):
for token in tokens:
if token.isalpha():
yield token.lower()
vocab = set(preprocess(tokens(wikitext)))
len(vocab)
```
%% Cell type:markdown id: tags:
## String-to-index mapping
%% Cell type:markdown id: tags:
One common task when processing text with neural networks is to encode words and other strings into contiguous ranges of integers, so that we can map them to the components of a vector. A standard pattern for doing this looks as follows:
%% Cell type:code id: tags:
``` python
w2i = {}
for token in tokens(wikitext):
if token not in w2i:
w2i[token] = len(w2i)
```
%% Cell type:markdown id: tags:
Assuming that we already have a representation of the vocabulary, we can also use a different pattern:
%% Cell type:code id: tags:
``` python
w2i = {w: i for i, w in enumerate(sorted(vocab))}
```
%% Cell type:markdown id: tags:
What index did the word *language* get?
%% Cell type:code id: tags:
``` python
w2i['language']
```
%% Cell type:markdown id: tags:
Sometimes we also need to invert the string-to-integer mapping:
%% Cell type:code id: tags:
``` python
i2w = {i: s for s, i in w2i.items()}
```
%% Cell type:markdown id: tags:
Decoding should be the inverse of encoding:
%% Cell type:code id: tags:
``` python
assert i2w[w2i['language']] == 'language'
```
%% Cell type:markdown id: tags:
## Power-law behaviour of language
%% Cell type:markdown id: tags:
Language data often exhibits a power-law behaviour. We want to check whether this also applies to the WikiText data. In particular, we want to check whether the word frequencies follow the expected Zipfian pattern. We start by collecting the frequencies:
%% Cell type:code id: tags:
``` python
from collections import Counter
counter = Counter(tokens(wikitext))
```
%% Cell type:markdown id: tags:
How often does the word *language* occur in the data?
%% Cell type:code id: tags:
``` python
counter['language']
```
%% Cell type:markdown id: tags:
Prepare `matplotlib` for plotting:
%% Cell type:code id: tags:
``` python
%matplotlib inline
import matplotlib.pyplot as plt
%config InlineBackend.figure_format = 'retina'
```
%% Cell type:markdown id: tags:
Produce the rank/frequency plot for the 30,000 most common words:
%% Cell type:code id: tags:
``` python
words, counts = zip(*counter.most_common(30000))
plt.xlabel('Rank')
plt.yscale('log')
plt.ylabel('Frequency')
plt.plot(range(len(words)), counts)
plt.show()
```
%% Cell type:markdown id: tags:
**🤔 Problem 4: Visualize Heaps’ law**
> Produce a plot that visualizes Heaps’ law for the WikiText dataset: on the $x$-axis, plot the text length; on the $y$-axis, plot the number of unique words encountered up to a given position in the text. How many new words, approximately, appear in the second half of the text?
%% Cell type:code id: tags:solution
``` python
unique_words = set()
ys = []
for token in tokens(wikitext):
unique_words.add(token)
ys.append(len(unique_words))
plt.xlabel('Length')
plt.ylabel('Vocabulary size')
plt.plot(range(len(ys)), ys)
plt.show()
print(ys[-1] - ys[len(ys)//2])
```
%% Cell type:markdown id: tags:
That’s all, folks!
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment