Newer
Older
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First let's change our current working directory to the folder where the data is located using `os.chdir`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import os\n",
"os.chdir(\"./ucsdHistory_raw\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's confirm that the changes are in effect by checking the current working directory:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"os.getcwd()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's open one of the newspaper's files and have a look at the contents. We'll start with the *Student Newspapers*, just because it's listed first alphabetically. We'll list all the files in the directory, open the first one and inspect the content by displaying the first 2000 characters in the file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"journal_name = 'Student Newspapers'\n",
"path = os.path.join(os.getcwd(), journal_name)\n",
"files = os.listdir(path)\n",
"files[:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`os.listdir()` returns the names of the files but not their path, which we need to be able to open them. For now we'll just use `os.path.join()` again."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"file = os.path.join(path, files[0])\n",
"with open(file, 'r') as fp:\n",
" content = fp.read()\n",
" \n",
"content[:2000]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Woops. Encoding error. Let's fix this by specifying the encoding"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"file = os.path.join(path, files[0])\n",
"with open(file, 'r', encoding = 'utf8') as fp:\n",
" content = fp.read()\n",
" \n",
"content[:2000]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, let's get rid of the hyphenation using regular expressions (for which we'll need the **re** package). We'll create a specific function for it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import re\n",
"def preprocess(text):\n",
" return re.sub('\\-\\n+', '', text)\n",
"\n",
"content = preprocess(content)\n",
"content[:2000]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we want to be able to load all the files in the directory and apply the preprocessing to them. To do that, we'll first define a function that will return the full path of all the files in the directory and will makes sure that we are only dealing with text files (so that we don't try to open a folder or another filetype that would cause an error):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def load_files(directory):\n",
" path = os.path.join(os.getcwd(), directory)\n",
" files = os.listdir(path)\n",
" files = [os.path.join(path, _) for _ in files if '.txt' in _]\n",
" return files\n",
"\n",
"load_files(path)[:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once we have all the files, we'll create a new function `load_data` to each file one by one, preprocess it and store the result in memory in an array"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def load_data(files):\n",
" X = []\n",
" for file in files:\n",
" with open(file, 'r', encoding = 'utf8') as fp:\n",
" content = fp.read()\n",
" content = preprocess(content)\n",
" X.append(content)\n",
" return X"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's actually run the function and get the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"files = load_files(journal_name)\n",
"documents = load_data(files)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"len(documents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we'll vectorize the documents. We'll only keep terms that appear in less than 80% of the documents and at least twice in the corpus. We'll limit the number of features to 5000."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import TfidfVectorizer"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"vectorizer = TfidfVectorizer(max_df=0.8, min_df=2, max_features=5000, stop_words='english')\n",
"X = vectorizer.fit_transform(documents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we'll apply non-negative matrix factorization to do topic modeling. We'll try with 25 topics first:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sklearn.decomposition import NMF\n",
"nmf = NMF(n_components=25, init = 'nndsvd').fit(X)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's have a look at nmf.components_ to understand the output and try to interprete the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"np.shape(nmf.components_)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nmf.components_"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nmf.components_[0].argsort()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"vocabulary = vectorizer.get_feature_names()\n",
"print(vocabulary[2499])\n",
"print(vocabulary[4960])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nmf.components_[0][2499]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nmf.components_[0][4960]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nmf.components_[0].argsort()[::-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's now print the top 10 words for the first topic:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"[vocabulary[i] for i in nmf.components_[0].argsort()[::-1][:10]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create a function that will allow us to do that for all the topics:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def display_topics(model, vocabulary, no_words):\n",
" for index, topic in enumerate(model.components_):\n",
" print(\"Topic\", index, \":\")\n",
" print(\" \".join([vocabulary[i] for i in topic.argsort()[::-1][:no_words]]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"display_topics(nmf, vocabulary, 15)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that we can also use nmf to get the distribution of each of our topic within a specific document (what percentage of document a concerns topic 1, 2 or 3? ) by normalizing the results of the NMF over the corpus:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"doc_topics = nmf.transform(X)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"np.shape(doc_topics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"doc_topics[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"sum(doc_topics[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"doc_topics = doc_topics / np.sum(doc_topics, axis=1, keepdims=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"doc_topics[0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's have a look at what metadata we can work with by opening the csv file corresponding to the corpus we're looking at. We will use the **pandas** package to load the csv file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import pandas as pd\n",
"# we've stored the name of the journal in a variable earlier, we can reuse this here so that we can more easily switch to another corpus in the future\n",
"df = pd.read_csv(journal_name + '.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at the columns"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df.columns"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And the first entries..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We notice that the filenames listed do not exactly correspond to the names of the raw text files we have used before, nor are they listed in the same order:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"files[:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For that reason we will need to process our filenames and match them to the appropriate row in the dataframe as well as to the appropriate topic distribution in the NMF matrix we created earlier from the corpus.\n",
"\n",
"We notice that the Object Unique ID of each row can be found in the filenames of the text files we have, so let's use that to match the raw text to the rows of the csv. Let's do a test with the first file:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"file_id = files[0].split('/')[-1].split('-')[0]\n",
"file_id"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df['Object Unique ID'].str.contains(file_id)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df[df['Object Unique ID'].str.contains(file_id)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's try to extract the date for this particular row. There are several date columns (BeginDate, EndDate, ...) but they all seem to be equivalent, so let's go with BeginDate..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"test_date = df['Begin date'][df['Object Unique ID'].str.contains(file_id)]\n",
"test_date"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are getting the right value, but the format of the output tells us that the data type returned is not exactly standard. Let's confirm this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"type(test_date)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a variable type specific to pandas, so we might run into trouble when trying to perform standard operations over it or sending it to some package's function. Let's make sure we only get the value and not the **pandas** Series cell:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"test_date = df['Begin date'][df['Object Unique ID'].str.contains(file_id)].values\n",
"print(test_date)\n",
"print(type(test_date))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Almost there..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"test_date = df['Begin date'][df['Object Unique ID'].str.contains(file_id)].values[0]\n",
"print(test_date)\n",
"print(type(test_date))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ok. So now we have a standard string. Which is good, but not ideal in case we want to perform some calculations on the date (substraction or extracting the month, year...). We can use the **dateparser** package to help us:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import dateparser\n",
"parsed = dateparser.parse(test_date)\n",
"print(type(parsed))\n",
"print(parsed)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A little parsing mistake here but we can handle that later. Let's iterate over all our files and store the results:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from collections import defaultdict\n",
"yearbook = defaultdict(list)\n",
"\n",
"for i, file in enumerate(files):\n",
" doc_year = dateparser.parse(df['Begin date'][df['Object Unique ID'].str.contains(file.split('/')[-1].split('-')[0])].values[0]).year\n",
" \n",
" # handles the 2k bug\n",
" if doc_year > 2018:\n",
" doc_year -= 100\n",
" \n",
" # fetches the corresponding distribution for the document. our files and topic distribution matrix have the same index\n",
" topic_distribution = doc_topics[i]\n",
" \n",
" # stores the result in an array\n",
" yearbook[doc_year].append(topic_distribution)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's compute the mean distribution of topics for each year (maybe absolute values would be better) and store the result in a dataframe"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"finals = {v: np.mean(yearbook[v], axis = 0) for v in yearbook}\n",
"res = pd.DataFrame.from_dict(finals)\n",
"res.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's transpose and plot the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"res.transpose().plot(figsize=(12,12))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}