Basic_text_processing.ipynb 10.4 KB
Newer Older
Marco Kuhlmann's avatar
Marco Kuhlmann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Basic text processing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The purpose of this notebook is to introduce you to some basic concepts and techniques for processing text data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "9R4lrT01ArUA"
   },
   "source": [
    "## Dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
31
    "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.\n",
Marco Kuhlmann's avatar
Marco Kuhlmann committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    "\n",
    "We start by opening the file and store its contents in a list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('wiki.train.tokens', encoding='utf-8') as fp:\n",
    "    wikitext = fp.readlines()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a sample line from the file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wikitext[1234]"
   ]
  },
  {
   "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?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tokenization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many tasks in natural language processing rely on first segmenting the raw text into words or word-like units. This task is called **tokenization**.\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",
Marco Kuhlmann's avatar
Marco Kuhlmann committed
86
    "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:"
Marco Kuhlmann's avatar
Marco Kuhlmann committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tokens(lines):\n",
    "    for line in lines:\n",
    "        for token in line.rstrip().split():\n",
    "            yield token"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With this, we can count the number of tokens in the dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sum(1 for t in tokens(wikitext))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Vocabulary"
   ]
  },
  {
   "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. 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.\n",
    "\n",
    "The set of unique words in a dataset or task is called the **vocabulary**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vocab = set(tokens(wikitext))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Show the size of the vocabulary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "len(vocab)"
   ]
  },
  {
   "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."
   ]
  },
  {
   "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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**🤔 Problem 3: Normalization**\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?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## String-to-index mapping"
   ]
  },
  {
   "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2i = {}\n",
    "for token in tokens(wikitext):\n",
    "    if token not in w2i:\n",
    "        w2i[token] = len(w2i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Assuming that we already have a representation of the vocabulary, we can also use a different pattern:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2i = {w: i for i, w in enumerate(sorted(vocab))}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What index did the word *language* get?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2i['language']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes we also need to invert the string-to-integer mapping:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "i2w = {i: s for s, i in w2i.items()}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Decoding should be the inverse of encoding:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert i2w[w2i['language']] == 'language'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Power-law behaviour of language"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "\n",
    "counter = Counter(tokens(wikitext))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How often does the word *language* occur in the data?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counter['language']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Prepare `matplotlib` for plotting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%config InlineBackend.figure_format = 'retina'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Produce the rank/frequency plot for the 30,000 most common words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words, counts = zip(*counter.most_common(30000))\n",
    "\n",
    "plt.xlabel('Rank')\n",
    "plt.yscale('log')\n",
    "plt.ylabel('Frequency')\n",
    "plt.plot(range(len(words)), counts)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**🤔 Problem 4: Visualize Heaps’ law**\n",
    "\n",
Marco Kuhlmann's avatar
Marco Kuhlmann committed
362
    "> 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?"
Marco Kuhlmann's avatar
Marco Kuhlmann committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That’s all, folks!"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "LM.ipynb",
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
382
   "display_name": "Python 3 (ipykernel)",
Marco Kuhlmann's avatar
Marco Kuhlmann committed
383
384
385
386
387
388
389
390
391
392
393
394
395
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
396
   "version": "3.8.2"
Marco Kuhlmann's avatar
Marco Kuhlmann committed
397
398
399
400
401
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}