/
LDA_study.ipynb
920 lines (920 loc) · 27.9 KB
/
LDA_study.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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Text Classification Using Topic Modelling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Topic modelling is a good intro to NLP. \n",
"Note that a lot of below is based on [this](https://towardsdatascience.com/nlp-extracting-the-main-topics-from-your-dataset-using-lda-in-minutes-21486f5aa925) article.\n",
"\n",
"My intention with this is\n",
"* learn topic modelling\n",
"* learn spacy\n",
"\n",
"As you will see (in earlier commits) the spacy part didn't pan out. It worked ok but the doc parsing was super slow for this volume. I'm not sure why that was, given I'd heard great things about it. I've tried to leave links on the previous commits to discussions around tuning spacy and some of the things I tried."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"from sklearn.datasets import fetch_20newsgroups\n",
"import gensim\n",
"from gensim.utils import simple_preprocess\n",
"from gensim.parsing.preprocessing import STOPWORDS\n",
"from nltk.stem import WordNetLemmatizer, SnowballStemmer\n",
"from nltk.stem.porter import *\n",
"\n",
"np.random.seed(42)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load the dataset\n",
"\n",
"We'll use a dataset of news articles grouped into 20 news categories - but just use 7 for this example.\n",
"I've tried to pick groups that should have a decent seperation."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"categories = [\n",
" 'comp.windows.x',\n",
" 'rec.autos',\n",
" 'rec.sport.baseball',\n",
" 'rec.sport.hockey',\n",
" 'sci.space',\n",
" 'soc.religion.christian',\n",
" 'talk.politics.guns'\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)\n",
"newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets looks at an example"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"From: SHOE@PHYSICS.watstar.uwaterloo.ca (Mark Shoesmith)\n",
"Subject: Re: Let's talk sticks...\n",
"Lines: 35\n",
"Organization: University of Waterloo\n",
"\n",
"In article <C50pt4.6CM@odin.corp.sgi.com> dptom@endor.corp.sgi.com (Tom Arnold) writes:\n",
"\n",
">Okay you hockey playing fans/finatics out there. I'm looking over the wide \n",
">range of aluminum sticks for the first time. I've been playing with pieces\n",
">of lumbar that seem to weigh alot and break after a few uses, so I'm \n",
">thinking of changing to an aluminum shaft so when I break the blade all I \n",
">have to do is change it. The problem is that there is such a wide reange of\n",
">models and selections out there that I'm not certain which to consider. Can\n",
">any of you post some of your suggestions and experiences with the aluminum \n",
">sticks? What is the difference between models? What do you like/dislike about\n",
">them? And, which brands are best?\n",
">\n",
">\n",
"\n",
"I've had, and still have a few aluminum sticks. I got my first when I was 15\n",
"(a Christian), and broke the shaft halfway through the season, two years \n",
"later. I bought another (a Canadian) at the beginning of the next season, \n",
"and I still have it. I also have an Easton, that a friend was getting rid \n",
"off, after giving up the game. I find that Easton blades are easier to get, \n",
"but all brands of blades are pretty well interchangeable. Watch out for \n",
"dried up bits of firewood, that some stores pass off as blades. In my \n",
"experiences, the blades of an aluminum break more often than regular sticks, \n",
"but I've only ever broken one aluminum shaft.\n",
"\n",
"I like aluminum sticks. The blades are quickly changed, even on the bench \n",
"if you have to. On the downside, the shaft won't break if you decide to \n",
"impale yourself on it :-)\n",
"\n",
"Ciao,\n",
"Mark S.\n",
"\n",
"\"This is between me and the vegetable\" - Rick Moranis in\n",
" Little Shop of Horrors\n",
"Mark Shoesmith\n",
"shoe@physics.watstar.uwaterloo.ca\n",
"\n"
]
}
],
"source": [
"print(newsgroups_train.data[6])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Group: rec.sport.hockey\n"
]
}
],
"source": [
"target_newsgroup = newsgroups_test.target_names[newsgroups_train.target[6]]\n",
"print('Group: {}'.format(target_newsgroup))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(4122,) (4122,)\n"
]
}
],
"source": [
"print(newsgroups_train.filenames.shape, newsgroups_train.target.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This should be enough rows normally. Though it is split over 7 categories which may not be enough. \n",
"Lets see how heavy each category is."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Counter({4: 593, 2: 597, 1: 594, 0: 593, 3: 600, 6: 546, 5: 599})"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import collections\n",
"collections.Counter(newsgroups_train.target)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I could map the keys to the category names but you can see by eye that it is a really balanced dataset."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Preprocessing"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We transform the data to basically optimise it so the ML algorithm recieves the strongest signal. \n",
"\n",
"* Tokenization: Split the text into sentences and the sentences into words. Lowercase the words and remove punctuation.\n",
"* Words that have fewer than 3 characters are removed.\n",
"* Remove stopwords: such as the, is, at, which, and on.\n",
"* Lemmatize: Words in third person are changed to first person and verbs in past and future tenses are changed into present.\n",
"* Stemming: Words are reduced to their root form.\n",
"\n",
"Lemmatizing is a mapping of the word to its base form i.e. went -> go. \n",
"Stemming is more of a function on the word such as removing the 'ing' from the end of words. \n",
"We do the lemmatizing and then stemming in the lemma may be a totally different spelt word (going -> go is similar but went -> go has a totally different spelling). \n",
"The stemming can often result in a 'invalid' word such as argue -> argu which the lemmatizing wouldn't accept."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"stemmer = SnowballStemmer('english') # Porter2 stemmer\n",
"\n",
"def lemmatize_stemming(text):\n",
" lemmatized = WordNetLemmatizer().lemmatize(text, pos='v')\n",
" return stemmer.stem(lemmatized)\n",
"\n",
"def preprocess(text):\n",
" \"\"\"\n",
" Tokenise and lemmatize text\n",
" \"\"\"\n",
" result=[]\n",
" for token in gensim.utils.simple_preprocess(text):\n",
" if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:\n",
" result.append(lemmatize_stemming(token))\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Check the output of the preprocessing"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['disk', 'fail', 'time', 'like', 'replac']\n"
]
}
],
"source": [
"doc_sample = 'This disk has failed many times. I would like to get it replaced.'\n",
"proc = preprocess(doc_sample)\n",
"print(proc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Preprocess all the messages we have (in parallel)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"import multiprocessing\n",
"pool = multiprocessing.Pool()\n",
"processed_docs = list(pool.map(preprocess, newsgroups_train.data))"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[['rlennip', 'mach', 'robert', 'lennip', 'subject', 'planet', 'imag', 'orbit', 'ether', 'twist', 'newsread', 'version', 'organ', 'wilfrid', 'laurier', 'univers', 'line', 'real', 'life'], ['rdetweil', 'richard', 'detweil', 'subject', 'card', 'mail', 'list', 'distribut', 'organ', 'hewlett', 'packard', 'line', 'count', 'interest', 'cardin', 'mail', 'list', 'find', 'start', 'know', 'thank', 'dick', 'detweil', 'rdetweil', 'hpdmd']]\n"
]
}
],
"source": [
"print(processed_docs[:2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create Bag of words\n",
"\n",
"A dictionary is the number of times a word appears in the training set.\n",
"A mapping between words and their integer ids."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"dictionary = gensim.corpora.Dictionary(processed_docs)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 ether\n",
"1 imag\n",
"2 laurier\n",
"3 lennip\n",
"4 life\n"
]
}
],
"source": [
"for i in range(5):\n",
" print(i, dictionary[i])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Filter out tokens that appear in\n",
"* less than 15 documents or\n",
"* more than 10% of documents\n",
"* after (1) and (2), keep only the first 100k most frequent tokens"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"dictionary.filter_extremes(no_below=15, no_above=0.1, keep_n=100000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Convert document (a list of words) into the bag-of-words format. \n",
"A list of (token_id, token_count) tuples"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(277, 1) - devic\n"
]
}
],
"source": [
"# i.e. the 3rd word from the 10th message\n",
"bow_doc_x = bow_corpus[10]\n",
"bow_word_x = 3\n",
"\n",
"print('{} - {}'.format(\n",
" bow_doc_x[5],\n",
" dictionary[bow_doc_x[bow_word_x][0]]\n",
"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Build the LDA Model\n",
"(Latent Dirichlet Allocation) \n",
"If observations are words collected into documents, it posits that each document is a mixture of a small number of topics and that each word's presence is attributable to one of the document's topics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* **alpha** and **eta** are hyperparameters that affect sparsity of the document-topic (theta) and topic-word (lambda) distributions. We will let these be the default values for now(default value is `1/num_topics`)\n",
" - Alpha is the per document topic distribution.\n",
" * High alpha: Every document has a mixture of all topics(documents appear similar to each other).\n",
" * Low alpha: Every document has a mixture of very few topics\n",
"\n",
" - Eta is the per topic word distribution.\n",
" * High eta: Each topic has a mixture of most words(topics appear similar to each other).\n",
" * Low eta: Each topic has a mixture of few words.\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"lda_model = gensim.models.LdaMulticore(\n",
" bow_corpus,\n",
" num_topics=7,\n",
" id2word=dictionary, \n",
" passes=10,\n",
" workers=4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluate the model"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(0,\n",
" '0.019*\"christian\" + 0.008*\"exist\" + 0.007*\"truth\" + 0.005*\"live\" + 0.005*\"life\" + 0.005*\"claim\" + 0.005*\"religion\" + 0.005*\"belief\" + 0.004*\"true\" + 0.004*\"absolut\"'),\n",
" (1,\n",
" '0.010*\"player\" + 0.007*\"season\" + 0.006*\"hockey\" + 0.006*\"score\" + 0.004*\"leagu\" + 0.004*\"goal\" + 0.004*\"basebal\" + 0.004*\"playoff\" + 0.004*\"defens\" + 0.004*\"second\"'),\n",
" (2,\n",
" '0.014*\"jesus\" + 0.012*\"church\" + 0.007*\"christ\" + 0.006*\"bibl\" + 0.006*\"christian\" + 0.006*\"hell\" + 0.006*\"faith\" + 0.005*\"cathol\" + 0.005*\"paul\" + 0.005*\"father\"'),\n",
" (3,\n",
" '0.023*\"window\" + 0.011*\"server\" + 0.011*\"widget\" + 0.010*\"file\" + 0.010*\"program\" + 0.009*\"motif\" + 0.008*\"applic\" + 0.008*\"display\" + 0.008*\"avail\" + 0.007*\"version\"'),\n",
" (4,\n",
" '0.013*\"file\" + 0.009*\"entri\" + 0.009*\"weapon\" + 0.008*\"gun\" + 0.008*\"firearm\" + 0.006*\"control\" + 0.005*\"crime\" + 0.005*\"govern\" + 0.005*\"output\" + 0.005*\"program\"'),\n",
" (5,\n",
" '0.024*\"space\" + 0.014*\"nasa\" + 0.010*\"orbit\" + 0.009*\"launch\" + 0.006*\"satellit\" + 0.005*\"mission\" + 0.005*\"earth\" + 0.005*\"data\" + 0.004*\"moon\" + 0.004*\"henri\"'),\n",
" (6,\n",
" '0.008*\"engin\" + 0.007*\"car\" + 0.005*\"price\" + 0.005*\"batf\" + 0.005*\"dealer\" + 0.005*\"drive\" + 0.004*\"compound\" + 0.004*\"scott\" + 0.004*\"buy\" + 0.003*\"children\"')]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lda_model.show_topics()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The show_topics shows what topics lda has found. You can see that the first is clearly about religion. The numbers show how much weight each word adds to a document being part of a topic. (TODO can you get negative numbers that are detrimental to classifying a topic?) \n",
"\n",
"This is an unsupervised algorithm so it never sees that target field we have. \n",
"Baseball isn't seperately represented. It looks the the language used is very similar to baseball. \n",
"However it has found 2 catagories for religion. I'm guessing Christians conversations have a decent split talking about solid entities like jesus and church, and then there are other conversations around spirituality and life in general."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"categories_map = {\n",
" 3: 'comp.windows.x',\n",
" 6: 'rec.autos',\n",
" -1: 'rec.sport.baseball',\n",
" 1: 'rec.sport.hockey',\n",
" 5: 'sci.space',\n",
" 2: 'soc.religion.christian',\n",
" 0: 'soc.religion.christian',\n",
" 4: 'talk.politics.guns'\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Testing model on unseen document"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"From: eggertj@moses.ll.mit.edu (Jim Eggert x6127 g41)\n",
"Subject: Re: Robin Lane Fox's _The Unauthorized Version_?\n",
"Reply-To: eggertj@ll.mit.edu\n",
"Organization: MIT Lincoln Lab - Group 41\n",
"Lines: 19\n",
"\n",
"In article <May.7.01.09.39.1993.14550@athos.rutgers.edu> iscleekk@nuscc.nus.sg (LEE KOK KIONG JAMES) writes:\n",
"| mpaul@unl.edu (marxhausen paul) writes:\n",
"| > My mom passed along a lengthy review she clipped regarding Robin Lane\n",
"| > Fox's book _The Unauthorized Version: Truth and Fiction in the Bible_,\n",
"|...\n",
"| I've read the book. Some parts were quite typical regarding its\n",
"| criticism of the bible as an inaccurate historical document,\n",
"| alt.altheism, etc carries typical responses, but not as vociferous as\n",
"| a.a. It does give an insight into how these historian (is he one... I \n",
"| don't have any biodata on him) work. I've not been able to understand/\n",
"| appreciate some of the arguments, something like, it mentions certain \n",
"| events, so it has to be after that event, and so on. \n",
"\n",
"Robin Lane Fox is a historian and a gardener. He has written several\n",
"history books, perhaps a recent one you might remember is \"The Search\n",
"for Alexander\". He has also written or edited several books on\n",
"gardening.\n",
"--\n",
"=Jim eggertj@ll.mit.edu (Jim Eggert)\n",
"\n",
"soc.religion.christian\n"
]
}
],
"source": [
"num = 2\n",
"unseen_document = newsgroups_test.data[num]\n",
"print(unseen_document)\n",
"print(newsgroups_test.target_names[newsgroups_test.target[num]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The document is from the soc.religion.christian group. Pushing it through the model gives the estimations of which catagories LDA thinks the document belongs to."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(0, 0.64716893), (3, 0.1975734), (1, 0.14305282)]\n"
]
}
],
"source": [
"# Data preprocessing step for the unseen document\n",
"bow_vector = dictionary.doc2bow(preprocess(unseen_document))\n",
"pred = sorted(lda_model[bow_vector], key=lambda tup: -1*tup[1])\n",
"print(pred)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"predicts soc.religion.christian with a probability of 64.72%\n"
]
}
],
"source": [
"print('predicts {} with a probability of {:.2f}%'.format(categories_map[pred[0][0]], pred[0][1]*100))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Correctly classifies as religion. It also shows a 20% chance of being about windows and 14% about hockey. \n",
"This is a multiclass classification so rather than it being x% chance of the doc falling into a category, it is more like the document is covered by a number of categories with religion being the most covered."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Check Accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have a test dataset we can use to check the accuracy. We preprocess and pass the documents through the model and see how many match up to the true topic."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"import multiprocessing\n",
"pool = multiprocessing.Pool()\n",
"test_processed_docs = list(pool.map(preprocess, newsgroups_test.data))"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"test_bow_corpus = [dictionary.doc2bow(doc) for doc in test_processed_docs]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the predicted values from the model"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"y_pred = []\n",
"for i, doc in enumerate(test_bow_corpus):\n",
" pred_all = sorted(lda_model[doc], key=lambda tup: -1*tup[1])\n",
" pred_cat = categories_map[pred_all[0][0]]\n",
" y_pred.append(newsgroups_test.target_names.index(pred_cat))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the ground truth values from the target field in the data"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"y_true = newsgroups_test.target"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['comp.windows.x',\n",
" 'rec.autos',\n",
" 'rec.sport.baseball',\n",
" 'rec.sport.hockey',\n",
" 'sci.space',\n",
" 'soc.religion.christian',\n",
" 'talk.politics.guns']"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"newsgroups_test.target_names"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Accuracy is the proportion of correct predictions of the model\n",
"\n",
"Accuracy = Number of correct predictions / Total number of predictions"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.6985052861830113"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.metrics import accuracy_score\n",
"accuracy_score(y_true, y_pred)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Accuracy is good for binary classification problems but less accurate in this case. It doesn't handle the belief in other topics that are covered in a document. \n",
"TODO: find a proper classification measure"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a confusion matrix to show. This is a grid of the predicted values on the horizontal and the true values on the vertical"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"# creating a confusion matrix \n",
"from sklearn.metrics import confusion_matrix \n",
"cm = confusion_matrix(y_true, y_pred)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Y_pred ->, y_true \\/"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[362, 11, 0, 8, 12, 2, 0],\n",
" [ 5, 317, 0, 33, 11, 27, 3],\n",
" [ 6, 8, 0, 356, 5, 18, 4],\n",
" [ 0, 7, 0, 382, 2, 6, 2],\n",
" [ 5, 13, 0, 3, 325, 25, 23],\n",
" [ 3, 3, 0, 3, 5, 381, 3],\n",
" [ 2, 174, 0, 5, 2, 32, 149]])"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that the diagonal has the high numbers, where the prediction was correct. \n",
"There are 174 messages where the model predicted hockey but the ground truth was cars. This could easily be where there is crossover with cars and sports. \n",
"People are discussing cars in the hockey newsgroup."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### pyLDAvis ### \n",
"Interactive topic model visualization\n",
"\n",
"This is a really good library for visuallising the topics and how the interact with each other. It sits ontop of the model and really pulls a ton of extra information out. \n",
"Note that running it freezes the python kernel as it launches a web server. (I've attached a screenshot)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"# import pyLDAvis.gensim\n",
"# pyLDAvis.enable_notebook()\n",
"# prepared = pyLDAvis.gensim.prepare(lda_model, bow_corpus, dictionary)\n",
"# pyLDAvis.show(prepared)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![title](pyLDAvis_screenshot.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* You can see 1 top left is the sports topics, large because it contains both hockey and baseball in a single topic\n",
"* 2, 3 and 6 are cars space and guns with a margin of crossover\n",
"* 7 and 5 are the religion topics with large crossover. I would have expected more, though I guess at some point a large overlap becomes seen as a large topic.\n",
"* 4 windows is out on its own"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conclusion"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This definately needs some tuning which I'll pick up in the future. Places for tuning are\n",
"* The Preprocessing\n",
" * Do we need both stemming and lemmatization\n",
" * Try a different stemmer. The SnowballStemmer is meant to strike a balance between being too aggressive or passive.\n",
"* Tune the LDA hyperparameters\n",
" * Alpha and eta. Also maybe the number of passes may produce different results\n",
"* Try a different model\n",
" * I see Non-negative matrix factorization being mentioned a lot\n",
" * RNN's are good at handling the abstract nature of language and they retain the sentence context. (Though last time I used an RNN I got better results with a non DL model)\n",
"\n",
"Ultimately this is a multi class classification problem and I would expect to get better results using supervised learning algorithms.\n",
"I was discussing this with someone and they mentioned using bigrams to handle the context that gets lost when using a bag of words. I would like to look into this, I thought about it later on and I'm hoping that using bigrams will give a sort of chain that the model can pick up on. \n",
"i.e. Now we have A, B, C. \n",
"With Bigrams we would have A, B, C and AB and BC, which give a sort of gives a relationship from A to C. \n",
"I'm not sure if the model will pick that relationship up but bigrams will definately add a stronger signal for the model."
]
}
],
"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.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}