"with open('wiki.train.tokens', encoding='utf-8') as fp:\n",
" wikitext = fp.readlines()"
"with open(\"wiki.train.tokens\", encoding=\"utf-8\") as f:\n",
" wikitext = f.readlines()"
]
},
{
...
...
@@ -63,16 +60,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"> **🤔 Problem 1: A close look at the data**\n",
">\n",
"> 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?"
"#### 🎈 Task 1: A close look at the data\n",
"\n",
"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",
"metadata": {},
"source": [
"## Tokenization"
"## Tokenisation"
]
},
{
...
...
@@ -81,8 +78,6 @@
"source": [
"Many tasks in natural language processing rely on first segmenting the raw text into words or word-like units. This task is called **tokenisation**.\n",
"\n",
"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.\n",
"\n",
"In real applications, we would have to tokenise 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-tokenised, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:"
]
},
...
...
@@ -94,7 +89,7 @@
"source": [
"def tokens(lines):\n",
" for line in lines:\n",
" for token in line.rstrip().split():\n",
" for token in line.split():\n",
" yield token"
]
},
...
...
@@ -125,7 +120,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"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. 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.\n",
"The term *word* is used ambiguously in natural language processing. It can either refer to a *token*, a word as it occurs in the running text, or to a *unique word*. We are interested in tokens when we want to count the length of a text, and in unique words when we want to compile a dictionary of all words in the text material.\n",
"\n",
"The set of unique words in a dataset or task is called the **vocabulary**."
]
...
...
@@ -159,25 +154,25 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"> **🤔 Problem 2: Missing words**\n",
">\n",
"> 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."
"#### 🎈 Task 2: Missing words\n",
"\n",
"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": "markdown",
"metadata": {},
"source": [
"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."
"For some natural language processing tasks, tokenisation 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 or apply some frequency cut-off."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**🤔 Problem 3: Normalization**\n",
"#### 🎈 Task 3: Normalisation\n",
"\n",
"> 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?"
"The term **text normalisation** refers to all kinds of processing that we apply to a text in order to bring it into a more standard, convenient form. Two standard normalisation techniques are lowercasing and the filtering-out of non-alphabetical tokens. What effect do these techniques have on the size of the vocabulary?"
]
},
{
...
...
@@ -191,7 +186,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"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:"
"One common task when processing text with neural networks is to encode words and other strings into integer IDs, so that we can map them to the components of a vector. A standard pattern for doing this looks as follows:"
]
},
{
...
...
@@ -210,7 +205,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Assuming that we already have a representation of the vocabulary, we can also use a different pattern:"
"Assuming that we already have the vocabulary, we can also use a different pattern:"
"> Produce a plot showing the number of words encountered after reading a certain number of tokens in the WikiText dataset. How many new words, approximately, appear in the second half of the text?"
"#### 🎈 Task 4: Visualise Heaps’ law\n",
"\n",
"Produce a plot showing the number of words encountered after reading a certain number of tokens in the WikiText dataset. How many new words, approximately, appear in the second half of the text?"
]
},
{
...
...
@@ -379,7 +372,7 @@
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
...
...
@@ -392,8 +385,7 @@
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
"pygments_lexer": "ipython3"
}
},
"nbformat": 4,
...
...
%% 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:
> 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?
#### 🎈 Task 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
## Tokenisation
%% 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 **tokenisation**.
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 tokenise 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-tokenised, 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
deftokens(lines):
forlineinlines:
fortokeninline.rstrip().split():
fortokeninline.split():
yieldtoken
```
%% Cell type:markdown id: tags:
With this, we can count the number of tokens in the dataset:
%% Cell type:code id: tags:
``` python
sum(1fortintokens(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. 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 term *word* is used ambiguously in natural language processing. It can either refer to a *token*, a word as it occurs in the running text, or to a *unique word*. We are interested in tokens when we want to count the length of a text, and in unique words 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.
#### 🎈 Task 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: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.
For some natural language processing tasks, tokenisation 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 or apply some frequency cut-off.
%% Cell type:markdown id: tags:
**🤔 Problem 3: Normalization**
#### 🎈 Task 3: Normalisation
> 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?
The term **text normalisation** refers to all kinds of processing that we apply to a text in order to bring it into a more standard, convenient form. Two standard normalisation 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: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:
One common task when processing text with neural networks is to encode words and other strings into integer IDs, 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={}
fortokenintokens(wikitext):
iftokennotinw2i:
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:
Assuming that we already have the vocabulary, we can also use a different pattern:
%% Cell type:code id: tags:
``` python
w2i={w:ifori,winenumerate(sorted(vocab))}
```
%% Cell type:markdown id: tags:
What index did the word *language* get?
%% Cell type:code id: tags:
``` python
w2i['language']
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:sfors,iinw2i.items()}
```
%% Cell type:markdown id: tags:
Decoding should be the inverse of encoding:
%% Cell type:code id: tags:
``` python
asserti2w[w2i['language']]=='language'
asserti2w[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
fromcollectionsimportCounter
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']
counter["language"]
```
%% Cell type:markdown id: tags:
Prepare `matplotlib` for plotting:
Prepare the plotting:
%% Cell type:code id: tags:
``` python
%matplotlibinline
importmatplotlib.pyplotasplt
%configInlineBackend.figure_format='svg'
%configInlineBackend.figure_format="svg"
```
%% 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.xlabel("Rank")
plt.yscale("log")
plt.ylabel("Frequency")
plt.plot(range(len(words)),counts)
plt.show()
```
%% Cell type:markdown id: tags:
> **🤔 Problem 4: Visualise Heaps’ law**
>
> Produce a plot showing the number of words encountered after reading a certain number of tokens in the WikiText dataset. How many new words, approximately, appear in the second half of the text?
#### 🎈 Task 4: Visualise Heaps’ law
Produce a plot showing the number of words encountered after reading a certain number of tokens in the WikiText dataset. How many new words, approximately, appear in the second half of the text?