-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathplot_document_classification_20newsgroups.html
948 lines (842 loc) · 94.2 KB
/
plot_document_classification_20newsgroups.html
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
<!DOCTYPE html>
<!-- data-theme below is forced to be "light" but should be changed if we use pydata-theme-sphinx in the future -->
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" data-content_root="../../" data-theme="light"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" data-content_root="../../" data-theme="light"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:title" content="Classification of text documents using sparse features" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://scikit-learn/stable/auto_examples/text/plot_document_classification_20newsgroups.html" />
<meta property="og:site_name" content="scikit-learn" />
<meta property="og:description" content="This is an example showing how scikit-learn can be used to classify documents by topics using a Bag of Words approach. This example uses a Tf-idf-weighted document-term sparse matrix to encode the ..." />
<meta property="og:image" content="https://scikit-learn.org/stable/_static/scikit-learn-logo-small.png" />
<meta property="og:image:alt" content="scikit-learn" />
<meta name="description" content="This is an example showing how scikit-learn can be used to classify documents by topics using a Bag of Words approach. This example uses a Tf-idf-weighted document-term sparse matrix to encode the ..." />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classification of text documents using sparse features — scikit-learn 1.4.2 documentation</title>
<link rel="canonical" href="https://scikit-learn.org/stable/auto_examples/text/plot_document_classification_20newsgroups.html" />
<link rel="shortcut icon" href="../../_static/favicon.ico"/>
<link rel="stylesheet" href="../../_static/css/vendor/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../../_static/copybutton.css" type="text/css" />
<link rel="stylesheet" href="../../_static/plot_directive.css" type="text/css" />
<link rel="stylesheet" href="../../https://fonts.googleapis.com/css?family=Vibur" type="text/css" />
<link rel="stylesheet" href="../../_static/jupyterlite_sphinx.css" type="text/css" />
<link rel="stylesheet" href="../../_static/sg_gallery.css" type="text/css" />
<link rel="stylesheet" href="../../_static/sg_gallery-binder.css" type="text/css" />
<link rel="stylesheet" href="../../_static/sg_gallery-dataframe.css" type="text/css" />
<link rel="stylesheet" href="../../_static/sg_gallery-rendered-html.css" type="text/css" />
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
<script src="../../_static/js/vendor/jquery-3.6.3.slim.min.js"></script>
<script src="../../_static/js/details-permalink.js"></script>
</head>
<body>
<nav id="navbar" class="sk-docs-navbar navbar navbar-expand-md navbar-light bg-light py-0">
<div class="container-fluid sk-docs-container px-0">
<a class="navbar-brand py-0" href="../../index.html">
<img
class="sk-brand-img"
src="../../_static/scikit-learn-logo-small.png"
alt="logo"/>
</a>
<button
id="sk-navbar-toggler"
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="sk-navbar-collapse collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="sk-nav-link nav-link" href="../../install.html">Install</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link" href="../../user_guide.html">User Guide</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link" href="../../modules/classes.html">API</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link" href="../index.html">Examples</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link" target="_blank" rel="noopener noreferrer" href="https://blog.scikit-learn.org/">Community</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../getting_started.html" >Getting Started</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../tutorial/index.html" >Tutorial</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../whats_new/v1.4.html" >What's new</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../glossary.html" >Glossary</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://scikit-learn.org/dev/developers/index.html" target="_blank" rel="noopener noreferrer">Development</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../faq.html" >FAQ</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../support.html" >Support</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../related_projects.html" >Related packages</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../roadmap.html" >Roadmap</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../governance.html" >Governance</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../about.html" >About us</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://github.com/scikit-learn/scikit-learn" >GitHub</a>
</li>
<li class="nav-item">
<a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://scikit-learn.org/dev/versions.html" >Other Versions and Download</a>
</li>
<li class="nav-item dropdown nav-more-item-dropdown">
<a class="sk-nav-link nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">More</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="sk-nav-dropdown-item dropdown-item" href="../../getting_started.html" >Getting Started</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../tutorial/index.html" >Tutorial</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../whats_new/v1.4.html" >What's new</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../glossary.html" >Glossary</a>
<a class="sk-nav-dropdown-item dropdown-item" href="https://scikit-learn.org/dev/developers/index.html" target="_blank" rel="noopener noreferrer">Development</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../faq.html" >FAQ</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../support.html" >Support</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../related_projects.html" >Related packages</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../roadmap.html" >Roadmap</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../governance.html" >Governance</a>
<a class="sk-nav-dropdown-item dropdown-item" href="../../about.html" >About us</a>
<a class="sk-nav-dropdown-item dropdown-item" href="https://github.com/scikit-learn/scikit-learn" >GitHub</a>
<a class="sk-nav-dropdown-item dropdown-item" href="https://scikit-learn.org/dev/versions.html" >Other Versions and Download</a>
</div>
</li>
</ul>
<div id="searchbox" role="search">
<div class="searchformwrapper">
<form class="search" action="../../search.html" method="get">
<input class="sk-search-text-input" type="text" name="q" aria-labelledby="searchlabel" />
<input class="sk-search-text-btn" type="submit" value="Go" />
</form>
</div>
</div>
</div>
</div>
</nav>
<div class="d-flex" id="sk-doc-wrapper">
<input type="checkbox" name="sk-toggle-checkbox" id="sk-toggle-checkbox">
<label id="sk-sidemenu-toggle" class="sk-btn-toggle-toc btn sk-btn-primary" for="sk-toggle-checkbox">Toggle Menu</label>
<div id="sk-sidebar-wrapper" class="border-right">
<div class="sk-sidebar-toc-wrapper">
<div class="btn-group w-100 mb-2" role="group" aria-label="rellinks">
<a href="index.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="Working with text documents">Prev</a><a href="index.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="Working with text documents">Up</a>
<a href="plot_document_clustering.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="Clustering text documents using k-means">Next</a>
</div>
<div class="alert alert-danger p-1 mb-2" role="alert">
<p class="text-center mb-0">
<strong>scikit-learn 1.4.2</strong><br/>
<a href="https://scikit-learn.org/dev/versions.html">Other versions</a>
</p>
</div>
<div class="alert alert-warning p-1 mb-2" role="alert">
<p class="text-center mb-0">
Please <a class="font-weight-bold" href="../../about.html#citing-scikit-learn"><string>cite us</string></a> if you use the software.
</p>
</div>
<div class="sk-sidebar-toc">
<ul>
<li><a class="reference internal" href="#">Classification of text documents using sparse features</a><ul>
<li><a class="reference internal" href="#loading-and-vectorizing-the-20-newsgroups-text-dataset">Loading and vectorizing the 20 newsgroups text dataset</a></li>
<li><a class="reference internal" href="#analysis-of-a-bag-of-words-document-classifier">Analysis of a bag-of-words document classifier</a><ul>
<li><a class="reference internal" href="#model-without-metadata-stripping">Model without metadata stripping</a></li>
<li><a class="reference internal" href="#model-with-metadata-stripping">Model with metadata stripping</a></li>
</ul>
</li>
<li><a class="reference internal" href="#benchmarking-classifiers">Benchmarking classifiers</a></li>
<li><a class="reference internal" href="#plot-accuracy-training-and-test-time-of-each-classifier">Plot accuracy, training and test time of each classifier</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="sk-page-content-wrapper">
<div class="sk-page-content container-fluid body px-md-3" role="main">
<div class="sphx-glr-download-link-note admonition note">
<p class="admonition-title">Note</p>
<p><a class="reference internal" href="#sphx-glr-download-auto-examples-text-plot-document-classification-20newsgroups-py"><span class="std std-ref">Go to the end</span></a>
to download the full example code or to run this example in your browser via JupyterLite or Binder</p>
</div>
<section class="sphx-glr-example-title" id="classification-of-text-documents-using-sparse-features">
<span id="sphx-glr-auto-examples-text-plot-document-classification-20newsgroups-py"></span><h1>Classification of text documents using sparse features<a class="headerlink" href="#classification-of-text-documents-using-sparse-features" title="Link to this heading">¶</a></h1>
<p>This is an example showing how scikit-learn can be used to classify documents by
topics using a <a class="reference external" href="https://en.wikipedia.org/wiki/Bag-of-words_model">Bag of Words approach</a>. This example uses a
Tf-idf-weighted document-term sparse matrix to encode the features and
demonstrates various classifiers that can efficiently handle sparse matrices.</p>
<p>For document analysis via an unsupervised learning approach, see the example
script <a class="reference internal" href="plot_document_clustering.html#sphx-glr-auto-examples-text-plot-document-clustering-py"><span class="std std-ref">Clustering text documents using k-means</span></a>.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Author: Peter Prettenhofer <[email protected]></span>
<span class="c1"># Olivier Grisel <[email protected]></span>
<span class="c1"># Mathieu Blondel <[email protected]></span>
<span class="c1"># Arturo Amor <[email protected]></span>
<span class="c1"># Lars Buitinck</span>
<span class="c1"># License: BSD 3 clause</span>
</pre></div>
</div>
<section id="loading-and-vectorizing-the-20-newsgroups-text-dataset">
<h2>Loading and vectorizing the 20 newsgroups text dataset<a class="headerlink" href="#loading-and-vectorizing-the-20-newsgroups-text-dataset" title="Link to this heading">¶</a></h2>
<p>We define a function to load data from <a class="reference internal" href="../../datasets/real_world.html#newsgroups-dataset"><span class="std std-ref">The 20 newsgroups text dataset</span></a>, which
comprises around 18,000 newsgroups posts on 20 topics split in two subsets:
one for training (or development) and the other one for testing (or for
performance evaluation). Note that, by default, the text samples contain some
message metadata such as <code class="docutils literal notranslate"><span class="pre">'headers'</span></code>, <code class="docutils literal notranslate"><span class="pre">'footers'</span></code> (signatures) and <code class="docutils literal notranslate"><span class="pre">'quotes'</span></code>
to other posts. The <code class="docutils literal notranslate"><span class="pre">fetch_20newsgroups</span></code> function therefore accepts a
parameter named <code class="docutils literal notranslate"><span class="pre">remove</span></code> to attempt stripping such information that can make
the classification problem “too easy”. This is achieved using simple
heuristics that are neither perfect nor standard, hence disabled by default.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">time</span> <span class="kn">import</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a>
<span class="kn">from</span> <span class="nn">sklearn.datasets</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups" title="sklearn.datasets.fetch_20newsgroups" class="sphx-glr-backref-module-sklearn-datasets sphx-glr-backref-type-py-function"><span class="n">fetch_20newsgroups</span></a>
<span class="kn">from</span> <span class="nn">sklearn.feature_extraction.text</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer" title="sklearn.feature_extraction.text.TfidfVectorizer" class="sphx-glr-backref-module-sklearn-feature_extraction-text sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">TfidfVectorizer</span></a>
<span class="n">categories</span> <span class="o">=</span> <span class="p">[</span>
<span class="s2">"alt.atheism"</span><span class="p">,</span>
<span class="s2">"talk.religion.misc"</span><span class="p">,</span>
<span class="s2">"comp.graphics"</span><span class="p">,</span>
<span class="s2">"sci.space"</span><span class="p">,</span>
<span class="p">]</span>
<span class="k">def</span> <span class="nf">size_mb</span><span class="p">(</span><span class="n">docs</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">"utf-8"</span><span class="p">))</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">docs</span><span class="p">)</span> <span class="o">/</span> <span class="mf">1e6</span>
<span class="k">def</span> <span class="nf">load_dataset</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">remove</span><span class="o">=</span><span class="p">()):</span>
<span class="w"> </span><span class="sd">"""Load and vectorize the 20 newsgroups dataset."""</span>
<span class="n">data_train</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups" title="sklearn.datasets.fetch_20newsgroups" class="sphx-glr-backref-module-sklearn-datasets sphx-glr-backref-type-py-function"><span class="n">fetch_20newsgroups</span></a><span class="p">(</span>
<span class="n">subset</span><span class="o">=</span><span class="s2">"train"</span><span class="p">,</span>
<span class="n">categories</span><span class="o">=</span><span class="n">categories</span><span class="p">,</span>
<span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="n">random_state</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span>
<span class="n">remove</span><span class="o">=</span><span class="n">remove</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">data_test</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups" title="sklearn.datasets.fetch_20newsgroups" class="sphx-glr-backref-module-sklearn-datasets sphx-glr-backref-type-py-function"><span class="n">fetch_20newsgroups</span></a><span class="p">(</span>
<span class="n">subset</span><span class="o">=</span><span class="s2">"test"</span><span class="p">,</span>
<span class="n">categories</span><span class="o">=</span><span class="n">categories</span><span class="p">,</span>
<span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="n">random_state</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span>
<span class="n">remove</span><span class="o">=</span><span class="n">remove</span><span class="p">,</span>
<span class="p">)</span>
<span class="c1"># order of labels in `target_names` can be different from `categories`</span>
<span class="n">target_names</span> <span class="o">=</span> <span class="n">data_train</span><span class="o">.</span><span class="n">target_names</span>
<span class="c1"># split target in a training set and a test set</span>
<span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">data_train</span><span class="o">.</span><span class="n">target</span><span class="p">,</span> <span class="n">data_test</span><span class="o">.</span><span class="n">target</span>
<span class="c1"># Extracting features from the training data using a sparse vectorizer</span>
<span class="n">t0</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span>
<span class="n">vectorizer</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer" title="sklearn.feature_extraction.text.TfidfVectorizer" class="sphx-glr-backref-module-sklearn-feature_extraction-text sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">TfidfVectorizer</span></a><span class="p">(</span>
<span class="n">sublinear_tf</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">max_df</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">min_df</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">stop_words</span><span class="o">=</span><span class="s2">"english"</span>
<span class="p">)</span>
<span class="n">X_train</span> <span class="o">=</span> <span class="n">vectorizer</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">data_train</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
<span class="n">duration_train</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span> <span class="o">-</span> <span class="n">t0</span>
<span class="c1"># Extracting features from the test data using the same vectorizer</span>
<span class="n">t0</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span>
<span class="n">X_test</span> <span class="o">=</span> <span class="n">vectorizer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">data_test</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
<span class="n">duration_test</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span> <span class="o">-</span> <span class="n">t0</span>
<span class="n">feature_names</span> <span class="o">=</span> <span class="n">vectorizer</span><span class="o">.</span><span class="n">get_feature_names_out</span><span class="p">()</span>
<span class="k">if</span> <span class="n">verbose</span><span class="p">:</span>
<span class="c1"># compute size of loaded data</span>
<span class="n">data_train_size_mb</span> <span class="o">=</span> <span class="n">size_mb</span><span class="p">(</span><span class="n">data_train</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
<span class="n">data_test_size_mb</span> <span class="o">=</span> <span class="n">size_mb</span><span class="p">(</span><span class="n">data_test</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">data_train</span><span class="o">.</span><span class="n">data</span><span class="p">)</span><span class="si">}</span><span class="s2"> documents - "</span>
<span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">data_train_size_mb</span><span class="si">:</span><span class="s2">.2f</span><span class="si">}</span><span class="s2">MB (training set)"</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">data_test</span><span class="o">.</span><span class="n">data</span><span class="p">)</span><span class="si">}</span><span class="s2"> documents - </span><span class="si">{</span><span class="n">data_test_size_mb</span><span class="si">:</span><span class="s2">.2f</span><span class="si">}</span><span class="s2">MB (test set)"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">target_names</span><span class="p">)</span><span class="si">}</span><span class="s2"> categories"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"vectorize training done in </span><span class="si">{</span><span class="n">duration_train</span><span class="si">:</span><span class="s2">.3f</span><span class="si">}</span><span class="s2">s "</span>
<span class="sa">f</span><span class="s2">"at </span><span class="si">{</span><span class="n">data_train_size_mb</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">duration_train</span><span class="si">:</span><span class="s2">.3f</span><span class="si">}</span><span class="s2">MB/s"</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"n_samples: </span><span class="si">{</span><span class="n">X_train</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="si">}</span><span class="s2">, n_features: </span><span class="si">{</span><span class="n">X_train</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"vectorize testing done in </span><span class="si">{</span><span class="n">duration_test</span><span class="si">:</span><span class="s2">.3f</span><span class="si">}</span><span class="s2">s "</span>
<span class="sa">f</span><span class="s2">"at </span><span class="si">{</span><span class="n">data_test_size_mb</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">duration_test</span><span class="si">:</span><span class="s2">.3f</span><span class="si">}</span><span class="s2">MB/s"</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"n_samples: </span><span class="si">{</span><span class="n">X_test</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="si">}</span><span class="s2">, n_features: </span><span class="si">{</span><span class="n">X_test</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">return</span> <span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span><span class="p">,</span> <span class="n">feature_names</span><span class="p">,</span> <span class="n">target_names</span>
</pre></div>
</div>
</section>
<section id="analysis-of-a-bag-of-words-document-classifier">
<h2>Analysis of a bag-of-words document classifier<a class="headerlink" href="#analysis-of-a-bag-of-words-document-classifier" title="Link to this heading">¶</a></h2>
<p>We will now train a classifier twice, once on the text samples including
metadata and once after stripping the metadata. For both cases we will analyze
the classification errors on a test set using a confusion matrix and inspect
the coefficients that define the classification function of the trained
models.</p>
<section id="model-without-metadata-stripping">
<h3>Model without metadata stripping<a class="headerlink" href="#model-without-metadata-stripping" title="Link to this heading">¶</a></h3>
<p>We start by using the custom function <code class="docutils literal notranslate"><span class="pre">load_dataset</span></code> to load the data without
metadata stripping.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span><span class="p">,</span> <span class="n">feature_names</span><span class="p">,</span> <span class="n">target_names</span> <span class="o">=</span> <span class="n">load_dataset</span><span class="p">(</span>
<span class="n">verbose</span><span class="o">=</span><span class="kc">True</span>
<span class="p">)</span>
</pre></div>
</div>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>2034 documents - 3.98MB (training set)
1353 documents - 2.87MB (test set)
4 categories
vectorize training done in 0.376s at 10.591MB/s
n_samples: 2034, n_features: 7831
vectorize testing done in 0.235s at 12.185MB/s
n_samples: 1353, n_features: 7831
</pre></div>
</div>
<p>Our first model is an instance of the
<a class="reference internal" href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier"><code class="xref py py-class docutils literal notranslate"><span class="pre">RidgeClassifier</span></code></a> class. This is a linear
classification model that uses the mean squared error on {-1, 1} encoded
targets, one for each possible class. Contrary to
<a class="reference internal" href="../../modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" title="sklearn.linear_model.LogisticRegression"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogisticRegression</span></code></a>,
<a class="reference internal" href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier"><code class="xref py py-class docutils literal notranslate"><span class="pre">RidgeClassifier</span></code></a> does not
provide probabilistic predictions (no <code class="docutils literal notranslate"><span class="pre">predict_proba</span></code> method),
but it is often faster to train.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RidgeClassifier</span></a>
<span class="n">clf</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RidgeClassifier</span></a><span class="p">(</span><span class="n">tol</span><span class="o">=</span><span class="mf">1e-2</span><span class="p">,</span> <span class="n">solver</span><span class="o">=</span><span class="s2">"sparse_cg"</span><span class="p">)</span>
<span class="n">clf</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">pred</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
</pre></div>
</div>
<p>We plot the confusion matrix of this classifier to find if there is a pattern
in the classification errors.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">from</span> <span class="nn">sklearn.metrics</span> <span class="kn">import</span> <span class="n">ConfusionMatrixDisplay</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="matplotlib.pyplot.subplots" class="sphx-glr-backref-module-matplotlib-pyplot sphx-glr-backref-type-py-function"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<a href="../../modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html#sklearn.metrics.ConfusionMatrixDisplay.from_predictions" title="sklearn.metrics.ConfusionMatrixDisplay.from_predictions" class="sphx-glr-backref-module-sklearn-metrics-ConfusionMatrixDisplay sphx-glr-backref-type-py-method"><span class="n">ConfusionMatrixDisplay</span><span class="o">.</span><span class="n">from_predictions</span></a><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">pred</span><span class="p">,</span> <span class="n">ax</span><span class="o">=</span><span class="n">ax</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">xaxis</span><span class="o">.</span><span class="n">set_ticklabels</span><span class="p">(</span><span class="n">target_names</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">yaxis</span><span class="o">.</span><span class="n">set_ticklabels</span><span class="p">(</span><span class="n">target_names</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"Confusion Matrix for </span><span class="si">{</span><span class="n">clf</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="se">\n</span><span class="s2">on the original documents"</span>
<span class="p">)</span>
</pre></div>
</div>
<img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_001.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_001.png" alt="Confusion Matrix for RidgeClassifier on the original documents" class = "sphx-glr-single-img"/><p>The confusion matrix highlights that documents of the <code class="docutils literal notranslate"><span class="pre">alt.atheism</span></code> class are
often confused with documents with the class <code class="docutils literal notranslate"><span class="pre">talk.religion.misc</span></code> class and
vice-versa which is expected since the topics are semantically related.</p>
<p>We also observe that some documents of the <code class="docutils literal notranslate"><span class="pre">sci.space</span></code> class can be misclassified as
<code class="docutils literal notranslate"><span class="pre">comp.graphics</span></code> while the converse is much rarer. A manual inspection of those
badly classified documents would be required to get some insights on this
asymmetry. It could be the case that the vocabulary of the space topic could
be more specific than the vocabulary for computer graphics.</p>
<p>We can gain a deeper understanding of how this classifier makes its decisions
by looking at the words with the highest average feature effects:</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="k">def</span> <span class="nf">plot_feature_effects</span><span class="p">():</span>
<span class="c1"># learned coefficients weighted by frequency of appearance</span>
<span class="n">average_feature_effects</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">coef_</span> <span class="o">*</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.asarray.html#numpy.asarray" title="numpy.asarray" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">asarray</span></a><span class="p">(</span><span class="n">X_train</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span><span class="o">.</span><span class="n">ravel</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">label</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">target_names</span><span class="p">):</span>
<span class="n">top5</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.argsort.html#numpy.argsort" title="numpy.argsort" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">argsort</span></a><span class="p">(</span><span class="n">average_feature_effects</span><span class="p">[</span><span class="n">i</span><span class="p">])[</span><span class="o">-</span><span class="mi">5</span><span class="p">:][::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="n">top</span> <span class="o">=</span> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame" title="pandas.DataFrame" class="sphx-glr-backref-module-pandas sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span></a><span class="p">(</span><span class="n">feature_names</span><span class="p">[</span><span class="n">top5</span><span class="p">],</span> <span class="n">columns</span><span class="o">=</span><span class="p">[</span><span class="n">label</span><span class="p">])</span>
<span class="n">top_indices</span> <span class="o">=</span> <span class="n">top5</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">top</span><span class="p">[</span><span class="n">label</span><span class="p">]</span> <span class="o">=</span> <span class="n">feature_names</span><span class="p">[</span><span class="n">top5</span><span class="p">]</span>
<span class="n">top_indices</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html#numpy.concatenate" title="numpy.concatenate" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">concatenate</span></a><span class="p">((</span><span class="n">top_indices</span><span class="p">,</span> <span class="n">top5</span><span class="p">),</span> <span class="n">axis</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="n">top_indices</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html#numpy.unique" title="numpy.unique" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">unique</span></a><span class="p">(</span><span class="n">top_indices</span><span class="p">)</span>
<span class="n">predictive_words</span> <span class="o">=</span> <span class="n">feature_names</span><span class="p">[</span><span class="n">top_indices</span><span class="p">]</span>
<span class="c1"># plot feature effects</span>
<span class="n">bar_size</span> <span class="o">=</span> <span class="mf">0.25</span>
<span class="n">padding</span> <span class="o">=</span> <span class="mf">0.75</span>
<span class="n">y_locs</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html#numpy.arange" title="numpy.arange" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">arange</span></a><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">top_indices</span><span class="p">))</span> <span class="o">*</span> <span class="p">(</span><span class="mi">4</span> <span class="o">*</span> <span class="n">bar_size</span> <span class="o">+</span> <span class="n">padding</span><span class="p">)</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="matplotlib.pyplot.subplots" class="sphx-glr-backref-module-matplotlib-pyplot sphx-glr-backref-type-py-function"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">label</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">target_names</span><span class="p">):</span>
<span class="n">ax</span><span class="o">.</span><span class="n">barh</span><span class="p">(</span>
<span class="n">y_locs</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">-</span> <span class="mi">2</span><span class="p">)</span> <span class="o">*</span> <span class="n">bar_size</span><span class="p">,</span>
<span class="n">average_feature_effects</span><span class="p">[</span><span class="n">i</span><span class="p">,</span> <span class="n">top_indices</span><span class="p">],</span>
<span class="n">height</span><span class="o">=</span><span class="n">bar_size</span><span class="p">,</span>
<span class="n">label</span><span class="o">=</span><span class="n">label</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set</span><span class="p">(</span>
<span class="n">yticks</span><span class="o">=</span><span class="n">y_locs</span><span class="p">,</span>
<span class="n">yticklabels</span><span class="o">=</span><span class="n">predictive_words</span><span class="p">,</span>
<span class="n">ylim</span><span class="o">=</span><span class="p">[</span>
<span class="mi">0</span> <span class="o">-</span> <span class="mi">4</span> <span class="o">*</span> <span class="n">bar_size</span><span class="p">,</span>
<span class="nb">len</span><span class="p">(</span><span class="n">top_indices</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="mi">4</span> <span class="o">*</span> <span class="n">bar_size</span> <span class="o">+</span> <span class="n">padding</span><span class="p">)</span> <span class="o">-</span> <span class="mi">4</span> <span class="o">*</span> <span class="n">bar_size</span><span class="p">,</span>
<span class="p">],</span>
<span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="s2">"lower right"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"top 5 keywords per class:"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">top</span><span class="p">)</span>
<span class="k">return</span> <span class="n">ax</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">plot_feature_effects</span><span class="p">()</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s2">"Average feature effect on the original data"</span><span class="p">)</span>
</pre></div>
</div>
<img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_002.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_002.png" alt="Average feature effect on the original data" class = "sphx-glr-single-img"/><div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>top 5 keywords per class:
alt.atheism comp.graphics sci.space talk.religion.misc
0 keith graphics space christian
1 god university nasa com
2 atheists thanks orbit god
3 people does moon morality
4 caltech image access people
</pre></div>
</div>
<p>We can observe that the most predictive words are often strongly positively
associated with a single class and negatively associated with all the other
classes. Most of those positive associations are quite easy to interpret.
However, some words such as <code class="docutils literal notranslate"><span class="pre">"god"</span></code> and <code class="docutils literal notranslate"><span class="pre">"people"</span></code> are positively associated to
both <code class="docutils literal notranslate"><span class="pre">"talk.misc.religion"</span></code> and <code class="docutils literal notranslate"><span class="pre">"alt.atheism"</span></code> as those two classes expectedly
share some common vocabulary. Notice however that there are also words such as
<code class="docutils literal notranslate"><span class="pre">"christian"</span></code> and <code class="docutils literal notranslate"><span class="pre">"morality"</span></code> that are only positively associated with
<code class="docutils literal notranslate"><span class="pre">"talk.misc.religion"</span></code>. Furthermore, in this version of the dataset, the word
<code class="docutils literal notranslate"><span class="pre">"caltech"</span></code> is one of the top predictive features for atheism due to pollution
in the dataset coming from some sort of metadata such as the email addresses
of the sender of previous emails in the discussion as can be seen below:</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="n">data_train</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups" title="sklearn.datasets.fetch_20newsgroups" class="sphx-glr-backref-module-sklearn-datasets sphx-glr-backref-type-py-function"><span class="n">fetch_20newsgroups</span></a><span class="p">(</span>
<span class="n">subset</span><span class="o">=</span><span class="s2">"train"</span><span class="p">,</span> <span class="n">categories</span><span class="o">=</span><span class="n">categories</span><span class="p">,</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">42</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">data_train</span><span class="o">.</span><span class="n">data</span><span class="p">:</span>
<span class="k">if</span> <span class="s2">"caltech"</span> <span class="ow">in</span> <span class="n">doc</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">doc</span><span class="p">)</span>
<span class="k">break</span>
</pre></div>
</div>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>From: [email protected] (Jon Livesey)
Subject: Re: Morality? (was Re: <Political Atheists?)
Organization: sgi
Lines: 93
Distribution: world
NNTP-Posting-Host: solntze.wpd.sgi.com
In article <[email protected]>, [email protected] (Keith Allan Schneider) writes:
|> [email protected] (Jon Livesey) writes:
|>
|> >>>Explain to me
|> >>>how instinctive acts can be moral acts, and I am happy to listen.
|> >>For example, if it were instinctive not to murder...
|> >
|> >Then not murdering would have no moral significance, since there
|> >would be nothing voluntary about it.
|>
|> See, there you go again, saying that a moral act is only significant
|> if it is "voluntary." Why do you think this?
If you force me to do something, am I morally responsible for it?
|>
|> And anyway, humans have the ability to disregard some of their instincts.
Well, make up your mind. Is it to be "instinctive not to murder"
or not?
|>
|> >>So, only intelligent beings can be moral, even if the bahavior of other
|> >>beings mimics theirs?
|> >
|> >You are starting to get the point. Mimicry is not necessarily the
|> >same as the action being imitated. A Parrot saying "Pretty Polly"
|> >isn't necessarily commenting on the pulchritude of Polly.
|>
|> You are attaching too many things to the term "moral," I think.
|> Let's try this: is it "good" that animals of the same species
|> don't kill each other. Or, do you think this is right?
It's not even correct. Animals of the same species do kill
one another.
|>
|> Or do you think that animals are machines, and that nothing they do
|> is either right nor wrong?
Sigh. I wonder how many times we have been round this loop.
I think that instinctive bahaviour has no moral significance.
I am quite prepared to believe that higher animals, such as
primates, have the beginnings of a moral sense, since they seem
to exhibit self-awareness.
|>
|>
|> >>Animals of the same species could kill each other arbitarily, but
|> >>they don't.
|> >
|> >They do. I and other posters have given you many examples of exactly
|> >this, but you seem to have a very short memory.
|>
|> Those weren't arbitrary killings. They were slayings related to some
|> sort of mating ritual or whatnot.
So what? Are you trying to say that some killing in animals
has a moral significance and some does not? Is this your
natural morality>
|>
|> >>Are you trying to say that this isn't an act of morality because
|> >>most animals aren't intelligent enough to think like we do?
|> >
|> >I'm saying:
|> > "There must be the possibility that the organism - it's not
|> > just people we are talking about - can consider alternatives."
|> >
|> >It's right there in the posting you are replying to.
|>
|> Yes it was, but I still don't understand your distinctions. What
|> do you mean by "consider?" Can a small child be moral? How about
|> a gorilla? A dolphin? A platypus? Where is the line drawn? Does
|> the being need to be self aware?
Are you blind? What do you think that this sentence means?
"There must be the possibility that the organism - it's not
just people we are talking about - can consider alternatives."
What would that imply?
|>
|> What *do* you call the mechanism which seems to prevent animals of
|> the same species from (arbitrarily) killing each other? Don't
|> you find the fact that they don't at all significant?
I find the fact that they do to be significant.
jon.
</pre></div>
</div>
<p>Such headers, signature footers (and quoted metadata from previous messages)
can be considered side information that artificially reveals the newsgroup by
identifying the registered members and one would rather want our text
classifier to only learn from the “main content” of each text document instead
of relying on the leaked identity of the writers.</p>
</section>
<section id="model-with-metadata-stripping">
<h3>Model with metadata stripping<a class="headerlink" href="#model-with-metadata-stripping" title="Link to this heading">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">remove</span></code> option of the 20 newsgroups dataset loader in scikit-learn allows
to heuristically attempt to filter out some of this unwanted metadata that
makes the classification problem artificially easier. Be aware that such
filtering of the text contents is far from perfect.</p>
<p>Let us try to leverage this option to train a text classifier that does not
rely too much on this kind of metadata to make its decisions:</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="p">(</span>
<span class="n">X_train</span><span class="p">,</span>
<span class="n">X_test</span><span class="p">,</span>
<span class="n">y_train</span><span class="p">,</span>
<span class="n">y_test</span><span class="p">,</span>
<span class="n">feature_names</span><span class="p">,</span>
<span class="n">target_names</span><span class="p">,</span>
<span class="p">)</span> <span class="o">=</span> <span class="n">load_dataset</span><span class="p">(</span><span class="n">remove</span><span class="o">=</span><span class="p">(</span><span class="s2">"headers"</span><span class="p">,</span> <span class="s2">"footers"</span><span class="p">,</span> <span class="s2">"quotes"</span><span class="p">))</span>
<span class="n">clf</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RidgeClassifier</span></a><span class="p">(</span><span class="n">tol</span><span class="o">=</span><span class="mf">1e-2</span><span class="p">,</span> <span class="n">solver</span><span class="o">=</span><span class="s2">"sparse_cg"</span><span class="p">)</span>
<span class="n">clf</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">pred</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="matplotlib.pyplot.subplots" class="sphx-glr-backref-module-matplotlib-pyplot sphx-glr-backref-type-py-function"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<a href="../../modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html#sklearn.metrics.ConfusionMatrixDisplay.from_predictions" title="sklearn.metrics.ConfusionMatrixDisplay.from_predictions" class="sphx-glr-backref-module-sklearn-metrics-ConfusionMatrixDisplay sphx-glr-backref-type-py-method"><span class="n">ConfusionMatrixDisplay</span><span class="o">.</span><span class="n">from_predictions</span></a><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">pred</span><span class="p">,</span> <span class="n">ax</span><span class="o">=</span><span class="n">ax</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">xaxis</span><span class="o">.</span><span class="n">set_ticklabels</span><span class="p">(</span><span class="n">target_names</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">yaxis</span><span class="o">.</span><span class="n">set_ticklabels</span><span class="p">(</span><span class="n">target_names</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"Confusion Matrix for </span><span class="si">{</span><span class="n">clf</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="se">\n</span><span class="s2">on filtered documents"</span>
<span class="p">)</span>
</pre></div>
</div>
<img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_003.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_003.png" alt="Confusion Matrix for RidgeClassifier on filtered documents" class = "sphx-glr-single-img"/><p>By looking at the confusion matrix, it is more evident that the scores of the
model trained with metadata were over-optimistic. The classification problem
without access to the metadata is less accurate but more representative of the
intended text classification problem.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="n">_</span> <span class="o">=</span> <span class="n">plot_feature_effects</span><span class="p">()</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s2">"Average feature effects on filtered documents"</span><span class="p">)</span>
</pre></div>
</div>
<img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_004.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_004.png" alt="Average feature effects on filtered documents" class = "sphx-glr-single-img"/><div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>top 5 keywords per class:
alt.atheism comp.graphics sci.space talk.religion.misc
0 don graphics space god
1 people file like christian
2 say thanks nasa jesus
3 religion image orbit christians
4 post does launch wrong
</pre></div>
</div>
<p>In the next section we keep the dataset without metadata to compare several
classifiers.</p>
</section>
</section>
<section id="benchmarking-classifiers">
<h2>Benchmarking classifiers<a class="headerlink" href="#benchmarking-classifiers" title="Link to this heading">¶</a></h2>
<p>Scikit-learn provides many different kinds of classification algorithms. In
this section we will train a selection of those classifiers on the same text
classification problem and measure both their generalization performance
(accuracy on the test set) and their computation performance (speed), both at
training time and testing time. For such purpose we define the following
benchmarking utilities:</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">metrics</span>
<span class="kn">from</span> <span class="nn">sklearn.utils.extmath</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.utils.extmath.density.html#sklearn.utils.extmath.density" title="sklearn.utils.extmath.density" class="sphx-glr-backref-module-sklearn-utils-extmath sphx-glr-backref-type-py-function"><span class="n">density</span></a>
<span class="k">def</span> <span class="nf">benchmark</span><span class="p">(</span><span class="n">clf</span><span class="p">,</span> <span class="n">custom_name</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"_"</span> <span class="o">*</span> <span class="mi">80</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training: "</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">clf</span><span class="p">)</span>
<span class="n">t0</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span>
<span class="n">clf</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">train_time</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span> <span class="o">-</span> <span class="n">t0</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"train time: </span><span class="si">{</span><span class="n">train_time</span><span class="si">:</span><span class="s2">.3</span><span class="si">}</span><span class="s2">s"</span><span class="p">)</span>
<span class="n">t0</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span>
<span class="n">pred</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="n">test_time</span> <span class="o">=</span> <a href="https://docs.python.org/3/library/time.html#time.time" title="time.time" class="sphx-glr-backref-module-time sphx-glr-backref-type-py-function"><span class="n">time</span></a><span class="p">()</span> <span class="o">-</span> <span class="n">t0</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"test time: </span><span class="si">{</span><span class="n">test_time</span><span class="si">:</span><span class="s2">.3</span><span class="si">}</span><span class="s2">s"</span><span class="p">)</span>
<span class="n">score</span> <span class="o">=</span> <a href="../../modules/generated/sklearn.metrics.accuracy_score.html#sklearn.metrics.accuracy_score" title="sklearn.metrics.accuracy_score" class="sphx-glr-backref-module-sklearn-metrics sphx-glr-backref-type-py-function"><span class="n">metrics</span><span class="o">.</span><span class="n">accuracy_score</span></a><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">pred</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"accuracy: </span><span class="si">{</span><span class="n">score</span><span class="si">:</span><span class="s2">.3</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">clf</span><span class="p">,</span> <span class="s2">"coef_"</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"dimensionality: </span><span class="si">{</span><span class="n">clf</span><span class="o">.</span><span class="n">coef_</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"density: </span><span class="si">{</span><a href="../../modules/generated/sklearn.utils.extmath.density.html#sklearn.utils.extmath.density" title="sklearn.utils.extmath.density" class="sphx-glr-backref-module-sklearn-utils-extmath sphx-glr-backref-type-py-function"><span class="n">density</span></a><span class="p">(</span><span class="n">clf</span><span class="o">.</span><span class="n">coef_</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">()</span>
<span class="nb">print</span><span class="p">()</span>
<span class="k">if</span> <span class="n">custom_name</span><span class="p">:</span>
<span class="n">clf_descr</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">custom_name</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">clf_descr</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span>
<span class="k">return</span> <span class="n">clf_descr</span><span class="p">,</span> <span class="n">score</span><span class="p">,</span> <span class="n">train_time</span><span class="p">,</span> <span class="n">test_time</span>
</pre></div>
</div>
<p>We now train and test the datasets with 8 different classification models and
get performance results for each model. The goal of this study is to highlight
the computation/accuracy tradeoffs of different types of classifiers for
such a multi-class text classification problem.</p>
<p>Notice that the most important hyperparameters values were tuned using a grid
search procedure not shown in this notebook for the sake of simplicity. See
the example script
<a class="reference internal" href="../model_selection/plot_grid_search_text_feature_extraction.html#sphx-glr-auto-examples-model-selection-plot-grid-search-text-feature-extraction-py"><span class="std std-ref">Sample pipeline for text feature extraction and evaluation</span></a> # noqa: E501
for a demo on how such tuning can be done.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn.ensemble</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier" title="sklearn.ensemble.RandomForestClassifier" class="sphx-glr-backref-module-sklearn-ensemble sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RandomForestClassifier</span></a>
<span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" title="sklearn.linear_model.LogisticRegression" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">LogisticRegression</span></a><span class="p">,</span> <a href="../../modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier" title="sklearn.linear_model.SGDClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">SGDClassifier</span></a>
<span class="kn">from</span> <span class="nn">sklearn.naive_bayes</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.naive_bayes.ComplementNB.html#sklearn.naive_bayes.ComplementNB" title="sklearn.naive_bayes.ComplementNB" class="sphx-glr-backref-module-sklearn-naive_bayes sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">ComplementNB</span></a>
<span class="kn">from</span> <span class="nn">sklearn.neighbors</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier" title="sklearn.neighbors.KNeighborsClassifier" class="sphx-glr-backref-module-sklearn-neighbors sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">KNeighborsClassifier</span></a><span class="p">,</span> <a href="../../modules/generated/sklearn.neighbors.NearestCentroid.html#sklearn.neighbors.NearestCentroid" title="sklearn.neighbors.NearestCentroid" class="sphx-glr-backref-module-sklearn-neighbors sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">NearestCentroid</span></a>
<span class="kn">from</span> <span class="nn">sklearn.svm</span> <span class="kn">import</span> <a href="../../modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC" title="sklearn.svm.LinearSVC" class="sphx-glr-backref-module-sklearn-svm sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">LinearSVC</span></a>
<span class="n">results</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">clf</span><span class="p">,</span> <span class="n">name</span> <span class="ow">in</span> <span class="p">(</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" title="sklearn.linear_model.LogisticRegression" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">LogisticRegression</span></a><span class="p">(</span><span class="n">C</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">max_iter</span><span class="o">=</span><span class="mi">1000</span><span class="p">),</span> <span class="s2">"Logistic Regression"</span><span class="p">),</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.linear_model.RidgeClassifier.html#sklearn.linear_model.RidgeClassifier" title="sklearn.linear_model.RidgeClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RidgeClassifier</span></a><span class="p">(</span><span class="n">alpha</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span> <span class="n">solver</span><span class="o">=</span><span class="s2">"sparse_cg"</span><span class="p">),</span> <span class="s2">"Ridge Classifier"</span><span class="p">),</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier" title="sklearn.neighbors.KNeighborsClassifier" class="sphx-glr-backref-module-sklearn-neighbors sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">KNeighborsClassifier</span></a><span class="p">(</span><span class="n">n_neighbors</span><span class="o">=</span><span class="mi">100</span><span class="p">),</span> <span class="s2">"kNN"</span><span class="p">),</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier" title="sklearn.ensemble.RandomForestClassifier" class="sphx-glr-backref-module-sklearn-ensemble sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">RandomForestClassifier</span></a><span class="p">(),</span> <span class="s2">"Random Forest"</span><span class="p">),</span>
<span class="c1"># L2 penalty Linear SVC</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC" title="sklearn.svm.LinearSVC" class="sphx-glr-backref-module-sklearn-svm sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">LinearSVC</span></a><span class="p">(</span><span class="n">C</span><span class="o">=</span><span class="mf">0.1</span><span class="p">,</span> <span class="n">dual</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">max_iter</span><span class="o">=</span><span class="mi">1000</span><span class="p">),</span> <span class="s2">"Linear SVC"</span><span class="p">),</span>
<span class="c1"># L2 penalty Linear SGD</span>
<span class="p">(</span>
<a href="../../modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier" title="sklearn.linear_model.SGDClassifier" class="sphx-glr-backref-module-sklearn-linear_model sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">SGDClassifier</span></a><span class="p">(</span>
<span class="n">loss</span><span class="o">=</span><span class="s2">"log_loss"</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">1e-4</span><span class="p">,</span> <span class="n">n_iter_no_change</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">early_stopping</span><span class="o">=</span><span class="kc">True</span>
<span class="p">),</span>
<span class="s2">"log-loss SGD"</span><span class="p">,</span>
<span class="p">),</span>
<span class="c1"># NearestCentroid (aka Rocchio classifier)</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.neighbors.NearestCentroid.html#sklearn.neighbors.NearestCentroid" title="sklearn.neighbors.NearestCentroid" class="sphx-glr-backref-module-sklearn-neighbors sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">NearestCentroid</span></a><span class="p">(),</span> <span class="s2">"NearestCentroid"</span><span class="p">),</span>
<span class="c1"># Sparse naive Bayes classifier</span>
<span class="p">(</span><a href="../../modules/generated/sklearn.naive_bayes.ComplementNB.html#sklearn.naive_bayes.ComplementNB" title="sklearn.naive_bayes.ComplementNB" class="sphx-glr-backref-module-sklearn-naive_bayes sphx-glr-backref-type-py-class sphx-glr-backref-instance"><span class="n">ComplementNB</span></a><span class="p">(</span><span class="n">alpha</span><span class="o">=</span><span class="mf">0.1</span><span class="p">),</span> <span class="s2">"Complement naive Bayes"</span><span class="p">),</span>
<span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"="</span> <span class="o">*</span> <span class="mi">80</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="n">results</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">benchmark</span><span class="p">(</span><span class="n">clf</span><span class="p">,</span> <span class="n">name</span><span class="p">))</span>
</pre></div>
</div>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>================================================================================
Logistic Regression
________________________________________________________________________________
Training:
LogisticRegression(C=5, max_iter=1000)
train time: 0.168s
test time: 0.000629s
accuracy: 0.772
dimensionality: 5316
density: 1.0
================================================================================
Ridge Classifier
________________________________________________________________________________
Training:
RidgeClassifier(solver='sparse_cg')
train time: 0.0315s
test time: 0.000624s
accuracy: 0.76
dimensionality: 5316
density: 1.0
================================================================================
kNN
________________________________________________________________________________
Training:
KNeighborsClassifier(n_neighbors=100)
train time: 0.000895s
test time: 0.0878s
accuracy: 0.753
================================================================================
Random Forest
________________________________________________________________________________
Training:
RandomForestClassifier()
train time: 1.62s
test time: 0.0536s
accuracy: 0.704
================================================================================
Linear SVC
________________________________________________________________________________
Training:
LinearSVC(C=0.1, dual=False)
train time: 0.0309s
test time: 0.000612s
accuracy: 0.752
dimensionality: 5316
density: 1.0
================================================================================
log-loss SGD
________________________________________________________________________________
Training:
SGDClassifier(early_stopping=True, loss='log_loss', n_iter_no_change=3)
train time: 0.0266s
test time: 0.000574s
accuracy: 0.762
dimensionality: 5316
density: 1.0
================================================================================
NearestCentroid
________________________________________________________________________________
Training:
NearestCentroid()
train time: 0.00259s
test time: 0.00161s
accuracy: 0.748
================================================================================
Complement naive Bayes
________________________________________________________________________________
Training:
ComplementNB(alpha=0.1)
train time: 0.00175s
test time: 0.000466s
accuracy: 0.779
</pre></div>
</div>
</section>
<section id="plot-accuracy-training-and-test-time-of-each-classifier">
<h2>Plot accuracy, training and test time of each classifier<a class="headerlink" href="#plot-accuracy-training-and-test-time-of-each-classifier" title="Link to this heading">¶</a></h2>
<p>The scatter plots show the trade-off between the test accuracy and the
training and testing time of each classifier.</p>
<div class="highlight-Python notranslate"><div class="highlight"><pre><span></span><span class="n">indices</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html#numpy.arange" title="numpy.arange" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">arange</span></a><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">results</span><span class="p">))</span>
<span class="n">results</span> <span class="o">=</span> <span class="p">[[</span><span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">results</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)]</span>
<span class="n">clf_names</span><span class="p">,</span> <span class="n">score</span><span class="p">,</span> <span class="n">training_time</span><span class="p">,</span> <span class="n">test_time</span> <span class="o">=</span> <span class="n">results</span>
<span class="n">training_time</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.array" title="numpy.array" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">array</span></a><span class="p">(</span><span class="n">training_time</span><span class="p">)</span>
<span class="n">test_time</span> <span class="o">=</span> <a href="https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.array" title="numpy.array" class="sphx-glr-backref-module-numpy sphx-glr-backref-type-py-function"><span class="n">np</span><span class="o">.</span><span class="n">array</span></a><span class="p">(</span><span class="n">test_time</span><span class="p">)</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax1</span> <span class="o">=</span> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="matplotlib.pyplot.subplots" class="sphx-glr-backref-module-matplotlib-pyplot sphx-glr-backref-type-py-function"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span>
<span class="n">ax1</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">score</span><span class="p">,</span> <span class="n">training_time</span><span class="p">,</span> <span class="n">s</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
<span class="n">ax1</span><span class="o">.</span><span class="n">set</span><span class="p">(</span>
<span class="n">title</span><span class="o">=</span><span class="s2">"Score-training time trade-off"</span><span class="p">,</span>
<span class="n">yscale</span><span class="o">=</span><span class="s2">"log"</span><span class="p">,</span>
<span class="n">xlabel</span><span class="o">=</span><span class="s2">"test accuracy"</span><span class="p">,</span>
<span class="n">ylabel</span><span class="o">=</span><span class="s2">"training time (s)"</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax2</span> <span class="o">=</span> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="matplotlib.pyplot.subplots" class="sphx-glr-backref-module-matplotlib-pyplot sphx-glr-backref-type-py-function"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">score</span><span class="p">,</span> <span class="n">test_time</span><span class="p">,</span> <span class="n">s</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">set</span><span class="p">(</span>
<span class="n">title</span><span class="o">=</span><span class="s2">"Score-test time trade-off"</span><span class="p">,</span>
<span class="n">yscale</span><span class="o">=</span><span class="s2">"log"</span><span class="p">,</span>
<span class="n">xlabel</span><span class="o">=</span><span class="s2">"test accuracy"</span><span class="p">,</span>
<span class="n">ylabel</span><span class="o">=</span><span class="s2">"test time (s)"</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">txt</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">clf_names</span><span class="p">):</span>
<span class="n">ax1</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">txt</span><span class="p">,</span> <span class="p">(</span><span class="n">score</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">training_time</span><span class="p">[</span><span class="n">i</span><span class="p">]))</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">txt</span><span class="p">,</span> <span class="p">(</span><span class="n">score</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">test_time</span><span class="p">[</span><span class="n">i</span><span class="p">]))</span>
</pre></div>
</div>
<ul class="sphx-glr-horizontal">
<li><img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_005.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_005.png" alt="Score-training time trade-off" class = "sphx-glr-multi-img"/></li>
<li><img src="../../_images/sphx_glr_plot_document_classification_20newsgroups_006.png" srcset="../../_images/sphx_glr_plot_document_classification_20newsgroups_006.png" alt="Score-test time trade-off" class = "sphx-glr-multi-img"/></li>
</ul>
<p>The naive Bayes model has the best trade-off between score and
training/testing time, while Random Forest is both slow to train, expensive to
predict and has a comparatively bad accuracy. This is expected: for
high-dimensional prediction problems, linear models are often better suited as
most problems become linearly separable when the feature space has 10,000
dimensions or more.</p>
<p>The difference in training speed and accuracy of the linear models can be
explained by the choice of the loss function they optimize and the kind of
regularization they use. Be aware that some linear models with the same loss
but a different solver or regularization configuration may yield different
fitting times and test accuracy. We can observe on the second plot that once
trained, all linear models have approximately the same prediction speed which
is expected because they all implement the same prediction function.</p>
<p>KNeighborsClassifier has a relatively low accuracy and has the highest testing
time. The long prediction time is also expected: for each prediction the model
has to compute the pairwise distances between the testing sample and each
document in the training set, which is computationally expensive. Furthermore,
the “curse of dimensionality” harms the ability of this model to yield
competitive accuracy in the high dimensional feature space of text
classification problems.</p>
<p class="sphx-glr-timing"><strong>Total running time of the script:</strong> (0 minutes 6.507 seconds)</p>
<div class="sphx-glr-footer sphx-glr-footer-example docutils container" id="sphx-glr-download-auto-examples-text-plot-document-classification-20newsgroups-py">
<div class="binder-badge docutils container">
<a class="reference external image-reference" href="https://mybinder.org/v2/gh/scikit-learn/scikit-learn/1.4.X?urlpath=lab/tree/notebooks/auto_examples/text/plot_document_classification_20newsgroups.ipynb"><img alt="Launch binder" src="../../_images/binder_badge_logo31.svg" width="150px" /></a>
</div>
<div class="lite-badge docutils container">
<a class="reference external image-reference" href="../../lite/lab/?path=auto_examples/text/plot_document_classification_20newsgroups.ipynb"><img alt="Launch JupyterLite" src="../../_images/jupyterlite_badge_logo31.svg" width="150px" /></a>
</div>
<div class="sphx-glr-download sphx-glr-download-jupyter docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/7ff1697c60d48929305821f39296dbb9/plot_document_classification_20newsgroups.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Jupyter</span> <span class="pre">notebook:</span> <span class="pre">plot_document_classification_20newsgroups.ipynb</span></code></a></p>
</div>
<div class="sphx-glr-download sphx-glr-download-python docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/b95d2be91f59162cfa269bdb32134d31/plot_document_classification_20newsgroups.py"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Python</span> <span class="pre">source</span> <span class="pre">code:</span> <span class="pre">plot_document_classification_20newsgroups.py</span></code></a></p>
</div>
</div>
<p class="rubric">Related examples</p>
<div class="sphx-glr-thumbnails"><div class="sphx-glr-thumbcontainer" tooltip="The dataset used in this example is 20newsgroups_dataset which will be automatically downloaded..."><img alt="" src="../../_images/sphx_glr_plot_grid_search_text_feature_extraction_thumb.png" />
<p><a class="reference internal" href="../model_selection/plot_grid_search_text_feature_extraction.html#sphx-glr-auto-examples-model-selection-plot-grid-search-text-feature-extraction-py"><span class="std std-ref">Sample pipeline for text feature extraction and evaluation</span></a></p>
<div class="sphx-glr-thumbnail-title">Sample pipeline for text feature extraction and evaluation</div>
</div><div class="sphx-glr-thumbcontainer" tooltip="This example demonstrates the Spectral Co-clustering algorithm on the twenty newsgroups dataset..."><img alt="" src="../../_images/sphx_glr_plot_bicluster_newsgroups_thumb.png" />
<p><a class="reference internal" href="../bicluster/plot_bicluster_newsgroups.html#sphx-glr-auto-examples-bicluster-plot-bicluster-newsgroups-py"><span class="std std-ref">Biclustering documents with the Spectral Co-clustering algorithm</span></a></p>
<div class="sphx-glr-thumbnail-title">Biclustering documents with the Spectral Co-clustering algorithm</div>
</div><div class="sphx-glr-thumbcontainer" tooltip="This is an example showing how the scikit-learn API can be used to cluster documents by topics ..."><img alt="" src="../../_images/sphx_glr_plot_document_clustering_thumb.png" />
<p><a class="reference internal" href="plot_document_clustering.html#sphx-glr-auto-examples-text-plot-document-clustering-py"><span class="std std-ref">Clustering text documents using k-means</span></a></p>
<div class="sphx-glr-thumbnail-title">Clustering text documents using k-means</div>
</div><div class="sphx-glr-thumbcontainer" tooltip="In this example we illustrate text vectorization, which is the process of representing non-nume..."><img alt="" src="../../_images/sphx_glr_plot_hashing_vs_dict_vectorizer_thumb.png" />
<p><a class="reference internal" href="plot_hashing_vs_dict_vectorizer.html#sphx-glr-auto-examples-text-plot-hashing-vs-dict-vectorizer-py"><span class="std std-ref">FeatureHasher and DictVectorizer Comparison</span></a></p>
<div class="sphx-glr-thumbnail-title">FeatureHasher and DictVectorizer Comparison</div>
</div><div class="sphx-glr-thumbcontainer" tooltip="The dataset used in this example is a preprocessed excerpt of the "Labeled Faces in the Wild", ..."><img alt="" src="../../_images/sphx_glr_plot_face_recognition_thumb.png" />
<p><a class="reference internal" href="../applications/plot_face_recognition.html#sphx-glr-auto-examples-applications-plot-face-recognition-py"><span class="std std-ref">Faces recognition example using eigenfaces and SVMs</span></a></p>
<div class="sphx-glr-thumbnail-title">Faces recognition example using eigenfaces and SVMs</div>
</div></div><p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p>
</section>
</section>
</div>
<div class="container">
<footer class="sk-content-footer">
© 2007 - 2024, scikit-learn developers (BSD License).
<a href="../../_sources/auto_examples/text/plot_document_classification_20newsgroups.rst.txt" rel="nofollow">Show this page source</a>
</footer>
</div>
</div>
</div>
<script src="../../_static/js/vendor/bootstrap.min.js"></script>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-22606712-2', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script defer data-domain="scikit-learn.org" src="https://views.scientific-python.org/js/script.js">
</script>
<script src="../../_static/clipboard.min.js"></script>
<script src="../../_static/copybutton.js"></script>
<script>
$(document).ready(function() {
/* Add a [>>>] button on the top-right corner of code samples to hide
* the >>> and ... prompts and the output and thus make the code
* copyable. */
var div = $('.highlight-python .highlight,' +
'.highlight-python3 .highlight,' +
'.highlight-pycon .highlight,' +
'.highlight-default .highlight')
var pre = div.find('pre');
// get the styles from the current theme
pre.parent().parent().css('position', 'relative');
// create and add the button to all the code blocks that contain >>>
div.each(function(index) {
var jthis = $(this);
// tracebacks (.gt) contain bare text elements that need to be
// wrapped in a span to work with .nextUntil() (see later)
jthis.find('pre:has(.gt)').contents().filter(function() {
return ((this.nodeType == 3) && (this.data.trim().length > 0));
}).wrap('<span>');
});
/*** Add permalink buttons next to glossary terms ***/
$('dl.glossary > dt[id]').append(function() {
return ('<a class="headerlink" href="#' +
this.getAttribute('id') +
'" title="Permalink to this term">¶</a>');
});
});
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<script src="https://scikit-learn.org/versionwarning.js"></script>
</body>
</html>