forked from fbkarsdorp/python-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChapter 7 - Archiving and Searching.ipynb~
1261 lines (1261 loc) · 47 KB
/
Chapter 7 - Archiving and Searching.ipynb~
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
31
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
86
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"metadata": {
"name": "",
"signature": "sha256:b812b955eb6663112f1e4d0d2fd16d90f387b368bed7feac53d56e8c1a3f9270"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Chapter 7 - Searching large Collections of Text"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"-- *A Python Course for the Humanities*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Imagine you have collected a large number of documents for your research. A large collection of English novels from [Project Gutenberg](http://www.gutenberg.org/), for example, or all volumes of the *New York Times* from 1987 until 2007 (see [here](https://catalog.ldc.upenn.edu/LDC2008T19)). The *New York Times* corpus contains over 1.8 million articles. If on average each article consists of only 500 words (the actual number will probably be higher), the complete corpus will contain about 900 million words. How can we search through such large collections of text? How can we efficiently find the information we are looking for? \n",
"\n",
"These questions are central to the current chapter. We will discuss important concepts from *Information Retrieval* to index and search collections (of text), such as the *inverted index* and the ranking metric *Okapi BM25*. This wouldn't be a Python course if you didn't have to implement all discussed techniques and methods. We will implement an important search algorithm which allows you to efficiently and reliably extract information from corpora. Along the way we will discuss quite some new and important programming techniques and constructs. We will also further our knowledge about the framework of Object Oriented Programming or OOP. We have quite some ground to cover, so let's get started."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Indexing Collections of Text"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> Information Retrieval (IR) is finding material (usually documents) of an unstructured nature (usually text) that satisfies an information need from within large collections (usually stored on computers. (Manning, NLP course, coursera)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The field of Information Retrieval (IR) deals with developing techniques that allow users to efficiently search through large collections (of text) to find documents that are relevant to the question a particular user has. These days we almost immediately think of *web search* in the context of IR, but there are many other use case scenarios, such as E-mail search, searching for music (e.g. Spotify) or searching for content on your laptop. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![caption](files/images/IR-schema.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Most search models in Information Retrieval are similar to the schema above. We have a collection of items, text documents, for example, that are indexed using an indexer with a particular indexing schema. Given a user query, the index is used to retrieve $k$ documents which, after scoring and sorting, are presented to the user. This might seem all a little abstract, but it will all become clear once we start implementing our own IR system.\n",
"\n",
"Consider a newspaper collection covering the complete 20th century. In this collection we would like to find all documents that mention [Albert Einstein](https://en.wikipedia.org/wiki/Albert_einstein) and [Edwin Hubble](https://en.wikipedia.org/wiki/Edwin_Hubble) but not [Enrico Fermi](https://en.wikipedia.org/wiki/Enrico_Fermi). Those of you familiar with the unix search tool [grep](https://en.wikipedia.org/wiki/Grep) might argue that we could simply use grep to search for all documents that contain both Einstein and Hubble and then filter out those documents that mention Fermi. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Come up with at least two reasons why searching with grep is not a good option."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Term Document Incidence Matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To efficiently give an answer to such queries we need to come up with another representation of our collection instead of plain text. Have a look at the following table.\n",
"\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>12-11-1928</th>\n",
" <th>04-04-1946</th>\n",
" <th>03-11-1983</th>\n",
" <th>19-01-1999</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>Einstein</th>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Hubble</th>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Fermi</th>\n",
" <td> 1</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Winfrey</th>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Dylan</th>\n",
" <td> 0</td>\n",
" <td> 0</td>\n",
" <td> 1</td>\n",
" <td> 1</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"\n",
"This table is called a *Term Document incidence matrix* where for each term (rows) we write down a 1 if a particular document (columns) contains that term and 0 otherwise. In this representation each term is represented by an incidence vector. If we want to extract all documents that mention Albert Einstein, we can use the binary vector `1100` of Einstein to quickly extract all documents mentioning Einstein. To find all documents containing both Einstein and Hubble we take the complement of the vectors of Einstein (1100) and Hubble (1110):\n",
"\n",
"`1100 AND 1110 = 1100` "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**a)** Given the incidence vectors of Einstein (1100), Hubble (1110) and Fermi (1000), what is the binary representation corresponding to the query `Einstein AND Hubble AND NOT Fermi`?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**b)** Can you implement the function `AND` that takes as argument two incidence vectors (represented a binary lists in Python) and returns the complement of the two?"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def AND(vector_a, vector_b):\n",
" # insert your code here\n",
" \n",
"# these tests should return True if your code is correct\n",
"print(AND([1, 1, 0, 0], [1, 1, 1, 0]) == [1, 1, 0, 0])\n",
"print(AND([1, 0, 0, 1, 0, 0, 1], [1, 1, 1, 0, 1, 0, 1]) == [1, 0, 0, 0, 0, 0, 1])"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**c)** Rewrite the function `AND` to allow it to take an arbitary number of incidence vectors."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def AND(*vectors):\n",
" # insert your code here \n",
"\n",
"# these tests should return True if your code is correct\n",
"print(AND([1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]) == [1, 0, 0, 0])\n",
"print(AND([1, 1, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 1, 0, 1]) == [0, 0, 0, 0, 0])"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**d)** Implement the function `NOT`. It takes as argument an incidence vector and returns a representation that can be used in combination with AND queries."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def NOT(vector):\n",
" # insert your code here\n",
"\n",
"# these tests should return True if your code is correct\n",
"print(AND([1, 1, 0, 0], [1, 1, 1, 0], NOT([1, 0, 0, 0])) == [0, 1, 0, 0])"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The binary representation allows us to efficiently search for documents containing particular terms of a search query. There are, however, still some problems that need to be overcome. Consider a document collection of 1 million documents where each document is about a thousand words long. On average such a collection contains approximately 500k unique terms. This means that if we try to build an incidence matrix, we would have to construct a matrix containing $500,000 \\times 1,000,000 =$ half a trillion 0's and 1's. Such a large matrix cannot be stored on a simple laptop."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**a)** Much of the information in the matrix is redundant. Why?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**b)** What would be a better representation of our matrix?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Inverted Index"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The *Inverted Index* is *the* key data structure in modern Information Retrieval. An inverted index is a structure in which for each unique term $t$ in our collection, we store a list of all document ID's that contain $t$. If we represent our small collection of newspapers in this way, it looks like this:\n",
"\n",
"`Einstein: [12-11-1928, 04-04-1946]` \n",
"`Hubble: [12-11-1928, 04-04-1946, 03-11-1983]` \n",
"`Fermi: [12-11-1928]` \n",
"`Winfrey: [19-01-1999]` \n",
"`Dylan: [03-11-1983, 19-01-1999]`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**a)** What would be a convenient and efficient data structure in Python to represent an inverted index?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**b)** We will implement a first version of an IR system. I choose to implement it as the class `IRSystem`. Implement the method `index_document`. It takes as argument a document ID and a list of words. The function should update the variable `tdf` in such a way that for each term it stores a set of all document IDs in which that term occurs."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import glob, os, re\n",
"from collections import defaultdict\n",
"\n",
"\n",
"def tokenize(text, lowercase=True):\n",
" text = text.lower() if lowercase else text\n",
" for match in re.finditer(r\"\\w+(\\.?\\w+)*\", text):\n",
" yield match.group()\n",
"\n",
" \n",
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several documents \n",
" with s.index_document(ID, text).\n",
" \"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(set)\n",
" self.doc_ids = []\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.doc_ids.append(doc_id)\n",
" # insert your code here\n",
" \n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
" \n",
"# these tests should return True if your code is correct\n",
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))\n",
"\n",
"print('The Ghost Kings 8184.txt' in s.tdf['master'])\n",
"print('Cleopatra 2769.txt' in s.tdf['children'])"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Query the Index"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have an efficient, sparse data structure to represent our collection, how can we use that stucture to efficiently process user queries? Our index is represented as a Python dictionary which allows us to query the index for single terms, using\n",
"\n",
" s = IRSystem()\n",
" s.tdf[term]\n",
"\n",
"which will return a set of all documents in which that term occurs. But how do we search for documents that contain two or more terms? Python's data structure `set` defines a convenient method called `intersection` with which we can extract all items common to two or more sets:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = {'a', 'b', 'c', 'd'}\n",
"b = {'c', 'a', 'e', 'f'}\n",
"print(a.intersection(b))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can make use of this method to implement the method `query` which takes as argument an arbitrary number of query terms and returns all documents in which those terms occur."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Implement the method `IRSystem.query(*terms)`. The method should return an iterable containing all ID's of the documents in which all query terms occur."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several documents \n",
" with s.index_document(ID, text). Then ask queries with \n",
" s.query('term1', 'term2') to retrieve the matching documents.\"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(set)\n",
" self.doc_ids = []\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.doc_ids.append(doc_id)\n",
" for word in words:\n",
" self.tdf[word].add(doc_id)\n",
"\n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
" \n",
" def query(self, *terms):\n",
" \"Query the system for documents in which all terms occur.\"\n",
" # insert your code here\n",
" \n",
"# these tests should return True if your code is correct\n",
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))\n",
"\n",
"print('Beatrice 3096.txt' in s.query(\"master\", \"children\"))\n",
"print('Fair Margaret 9780.txt' in s.query(\"eye\", \"father\", \"work\"))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our Information Retrieval system starts to look quite good. We have written functions to tokenize documents, index documents and query the index for documents. In the query method above, we made the simplifying assumption that as long as two documents contain a particular search term, they are equally relevant. However, our intuition says that documents that contain more instances of a particular term are more relevant than documents with less instances. To account for this intuition we need a way to score and sort our search results.\n",
"\n",
"Let's start with a very naive and simple scoring function: document frequency. This scoring function simply sums the document frequencies of each search term in a particular document:\n",
"\n",
"$$\\textrm{score}(q_1, q_2, \\ldots, q_n) = \\sum^n_{i=1} df(q_i)$$\n",
"\n",
"where $n$ is the number of search terms and $df$ the document frequency of term $q_i$ in a document.\n",
"\n",
"To compute this formula we need to obtain the frequency of each word in each document. The method `index_document` seems an appropriate place to extract these frequencies. For each term we store how often that term occurs in each document. Note that in the previous implementation of `index_document`, the variable `tdf` is represented by a dictionary with sets of document ID's as values. We will change this data structure to a structure that allows us to store the document frequencies:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from collections import Counter\n",
"\n",
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several documents \n",
" with s.index_document(ID, text). Then ask queries with \n",
" s.query('term1', 'term2') to retrieve the matching documents.\"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(Counter) # changed!\n",
" self.doc_ids = []\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.doc_ids.append(doc_id)\n",
" for word in words:\n",
" self.tdf[word][doc_id] += 1 # changed!\n",
"\n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read())) \n",
" \n",
" def query(self, *terms):\n",
" \"Query the system for documents in which all terms occur.\"\n",
" return set.intersection(*map(self.tdf.get, terms))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I represent the `tdf` variable as a dictionary with [Counter](https://docs.python.org/dev/library/collections.html#collections.Counter) objects as default values. The `Counter` object is a very convenient structure for counting hashable objects. As you can see, we only had to adjust two lines in our original system. Before we continue, make sure you understand what is happening here. We reinitialize our IR system:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's inspect the term-document frequency matrix:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s.tdf['master'].most_common(n=10)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The class `Counter` has a method called `most_common`. It returns the $n$ most common items in a `Counter` object. We have a data structure that stores the information about the frequency of words in documents. The next step will be to to adapt our query function in such a way that it returns a ranked list of documents where each document is sorted on the basis of the equation above."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**a)** The method `query` in the class definition below calls the method `score`. This method takes as arguments a document ID and an arbitrary number of terms. It returns the sum of the frequencies of these terms in this document. Implement the method `score`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several \n",
" documents with s.index_document(ID, text). Then ask queries \n",
" with s.query('term1', 'term2') to retrieve the top n matching \n",
" documents.\"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(Counter)\n",
" self.doc_ids = []\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.doc_ids.append(doc_id)\n",
" for word in words:\n",
" self.tdf[word][doc_id] += 1\n",
"\n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
" \n",
" def score(self, doc_id, *terms):\n",
" \"Score a document for a particular query using the sum of the term frequencies.\"\n",
" # insert your code here\n",
" \n",
" def query(self, *terms, n=10):\n",
" \"\"\"Query the system for documents in which all terms occur. Returns\n",
" the top n matching documents.\"\"\"\n",
" scores = {doc_id: self.score(doc_id, *terms) for doc_id in self.doc_ids}\n",
" return sorted(scores, key=scores.get, reverse=True)[:n]\n",
"\n",
"\n",
"# these tests should return True if your code is correct\n",
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))\n",
"\n",
"print(s.query(\"master\")[0] == 'The Ancient Allan 5746.txt')\n",
"print(s.query(\"egg\", \"shell\")[0] == 'Dawn 10892.txt')"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**b)** Give at least two reasons why this way of scoring and sorting our documents is probably not such a good idea, after all."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Double click this cell and write down your answer.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Okapi BM25"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our scoring method contains multiple flaws. Most worrying is that it does not control for the lengths of our documents. Needless to say, this greatly influences our final lists. We need to think harder about what makes it that a search term is more or less relevant for a particular document.\n",
"\n",
"The frequency with which terms occur in a document functions as an important cue to the importance of a document. The document is even more important when it contains many examples of this search term while the term occurs only in a limited number of other documents. In Information Retrieval a ranking metric that attempts to capture this intuition is [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25). The metric has proven to be one of the most successful ranking functions. In one of its many versions it is computed as follows:\n",
"\n",
"$$score(q_1, q_2, \\ldots, q_n) = \\sum^n_{i=1} IDF(q_i) \\cdot \\frac{df(q_i, D) \\cdot (k_1 + 1)}{df(q_i, D) + k_1 \\cdot (1 - b + b \\cdot \\frac{|D|}{\\textrm{avgdl}})}$$\n",
"\n",
"where $Q$ represents a query and $df(q_i, D)$ is the frequency of the i'th term in $Q$ in document $D$. $|D|$ is the length of document $D$ in number of word tokens and avgdl is the average document length. The parameters $b$ and $k_1$ are commonly set to $0.75$ and $1.2$, respectively. We compute the I(nverse) D(ocument) F(requency) weight using:\n",
"\n",
"$$IDF(q_i) = \\log \\frac{N - n(q_i) + 0.5}{n(q_i) + 0.5}$$\n",
"\n",
"where $N$ is the number of documents in the corpus and $n(q_i)$ the number of documents that contain $q_i$.\n",
"\n",
"We will implement this formula in our `score` method. Before we do that, we will first make a list of all the information we need to compute the formula:\n",
"\n",
"1. the frequency of a term $q_i$ in document $D$;\n",
"2. the length of document $D$;\n",
"3. the average length of all documents in the collection;\n",
"4. the IDF weight of a term $q_i$.\n",
"\n",
"Our current implementation already stores the document frequency of each term in each document (1). Thus, we only need to write code to extract the last three items: (2) the length of each document, (3) the average document length and (4) the IDF weight of each unique term."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Quiz!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**a)** In this exercize you have to add the length of each document in our collection to the IR system. Reimplement the `index_document` method. Besides updating the term-document frequencies of each term, it should update the `Counter` object `lengths` in such a way that for each document ID it stores the length of the document being indexed."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several \n",
" documents with s.index_document(ID, text). Then ask queries \n",
" with s.query('term1', 'term2') to retrieve the top n matching \n",
" documents.\"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(Counter)\n",
" self.lengths = Counter()\n",
" self.doc_ids = []\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.doc_ids.append(doc_id)\n",
" # insert your code here\n",
"\n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
" \n",
" def score(self, doc_id, *terms):\n",
" \"Score a document for a particular query using the sum of the term frequencies.\"\n",
" return sum(self.tdf[term][doc_id] for term in terms)\n",
" \n",
" def query(self, *terms, n=10):\n",
" \"\"\"Query the system for documents in which all terms occur. Returns\n",
" the top n matching documents.\"\"\"\n",
" scores = {doc_id: self.score(doc_id, *terms) for doc_id in self.doc_ids}\n",
" return sorted(scores, key=scores.get, reverse=True)[:n]\n",
"\n",
"\n",
"# these tests should return True if your code is correct\n",
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))\n",
"\n",
"print(s.lengths['Dawn 10892.txt'] == 192299)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
<<<<<<< HEAD
"**b)** Once we have obtained the document length for each document, computing the average document length is trivial. In this exercize we will focus on the IDF weights. To compute the IDF weight for a particular term $q_i$ we need to know two things:\n",
=======
"**b)** Once we have obtained the document length for each document, computing the average document length is trivial. In this exercise we will focus on the IDF weights. To compute the IDF weight for a particular term $q_i$ we need to know two things:\n",
>>>>>>> 74d405b678e41477451c9434a1ce3df98d27818a
"\n",
"1. how many documents $N$ there are in our collection;\n",
"2. in how many documents that term occurs: $n(q_i)$.\n",
"\n",
"We will implement a helper method called `_document_frequency`. It should return a dictionary in which we store for each term the number of documents in which that term occurs. You will also need to adapt the `index_document` method in such a way that the variable `N` represents the number of documents that have been indexed."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several \n",
" documents with s.index_document(ID, text). Then ask queries \n",
" with s.query('term1', 'term2') to retrieve the top n matching \n",
" documents.\"\"\"\n",
" \n",
" def __init__(self):\n",
" \"Initialize an IR Sytem.\"\n",
" self.tdf = defaultdict(Counter)\n",
" self.lengths = Counter()\n",
" self.doc_ids = []\n",
" self.N = 0\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
<<<<<<< HEAD
" self.doc_ids.append(doc_id)\n",
=======
>>>>>>> 74d405b678e41477451c9434a1ce3df98d27818a
" # insert you code here\n",
" \n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
"\n",
" def _document_frequency(self):\n",
" \"Return the document frequency for each term in self.tdf.\"\n",
" # insert your code here\n",
" \n",
" def score(self, doc_id, *terms):\n",
" \"Score a document for a particular query using the sum of the term frequencies.\"\n",
" return sum(self.tdf[term][doc_id] for term in terms)\n",
" \n",
" def query(self, *terms, n=10):\n",
" \"\"\"Query the system for documents in which all terms occur. Returns\n",
" the top n matching documents.\"\"\"\n",
" scores = {doc_id: self.score(doc_id, *terms) for doc_id in self.doc_ids}\n",
" return sorted(scores, key=scores.get, reverse=True)[:n]\n",
"\n",
"\n",
"# these tests should return True if your code is correct\n",
"s = IRSystem()\n",
"s.index_collection(glob.glob('data/haggard/*.txt'))\n",
"\n",
"print(s._document_frequency()['children'] == 59)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now have all the ingredients to compute the Okapi BM25 score. Lets put everything together and implement a complete version of our IR system:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import glob, os\n",
"from math import log\n",
"\n",
"class IRSystem:\n",
" \"\"\"A very simple Information Retrieval System. The constructor \n",
" s = IRSystem() builds an empty system. Next, index several documents \n",
" with s.index_document(text, url). Then ask queries with \n",
" s.query('term1', 'term2', n=10) to retrieve the top n \n",
" matching documents.\"\"\"\n",
" \n",
" def __init__(self, b=0.75, k1=1.2):\n",
" \"Initialize an IR Sytem.\"\n",
" self.N = 0\n",
" self.lengths = Counter()\n",
" self.tdf = defaultdict(Counter)\n",
" self.doc_ids = []\n",
" self.b = b\n",
" self.k1 = k1\n",
" self._all_set = False\n",
" \n",
" def __repr__(self):\n",
" return '<IRSystem(b={self.b}, k1={self.k1}, N={self.N})>'.format(self=self)\n",
" \n",
" def index_document(self, doc_id, words):\n",
" \"Add a new unindexed document to the system.\"\n",
" self.N += 1\n",
" self.doc_ids.append(doc_id)\n",
" for word in words:\n",
" self.tdf[word][doc_id] += 1\n",
" self.lengths[doc_id] += 1\n",
" self._all_set = False\n",
" \n",
" def index_collection(self, filenames):\n",
" \"Index a collection of documents.\"\n",
" for filename in filenames:\n",
" self.index_document(os.path.basename(filename), \n",
" tokenize(open(filename).read()))\n",
" \n",
" def _document_frequency(self):\n",
" \"Return the document frequency for each term in self.tdf.\"\n",
" return {term: len(documents) for term, documents in self.tdf.items()}\n",
" \n",
" def score(self, doc_id, *query):\n",
" \"Score a document for a particular query using Okapi BM25.\"\n",
" score = 0\n",
" length = self.lengths[doc_id]\n",
" for term in query:\n",
" tf = self.tdf[term][doc_id]\n",
" df = self.df.get(term, 0)\n",
" idf = log((self.N - df + 0.5) / (df + 0.5))\n",
" score += (idf * (tf * (self.k1 + 1)) / \n",
" (tf + self.k1 * (1 - self.b + (self.b * length / self.avg_len))))\n",
" return score\n",
" \n",
" def query(self, *query, n=10):\n",