forked from saundersg/Statistics-Notebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogisticRegression.html
1385 lines (1314 loc) · 102 KB
/
LogisticRegression.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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Logistic Regression</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cerulean.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<script src="site_libs/accessible-code-block-0.0.1/empty-anchor.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css" data-origin="pandoc">
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ background-color: #f8f8f8; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ef2929; } /* Alert */
code span.an { color: #8f5902; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #c4a000; } /* Attribute */
code span.bn { color: #0000cf; } /* BaseN */
code span.cf { color: #204a87; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4e9a06; } /* Char */
code span.cn { color: #000000; } /* Constant */
code span.co { color: #8f5902; font-style: italic; } /* Comment */
code span.cv { color: #8f5902; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #8f5902; font-weight: bold; font-style: italic; } /* Documentation */
code span.dt { color: #204a87; } /* DataType */
code span.dv { color: #0000cf; } /* DecVal */
code span.er { color: #a40000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #0000cf; } /* Float */
code span.fu { color: #000000; } /* Function */
code span.im { } /* Import */
code span.in { color: #8f5902; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #204a87; font-weight: bold; } /* Keyword */
code span.op { color: #ce5c00; font-weight: bold; } /* Operator */
code span.ot { color: #8f5902; } /* Other */
code span.pp { color: #8f5902; font-style: italic; } /* Preprocessor */
code span.sc { color: #000000; } /* SpecialChar */
code span.ss { color: #4e9a06; } /* SpecialString */
code span.st { color: #4e9a06; } /* String */
code span.va { color: #000000; } /* Variable */
code span.vs { color: #4e9a06; } /* VerbatimString */
code span.wa { color: #8f5902; font-weight: bold; font-style: italic; } /* Warning */
</style>
<script>
// apply pandoc div.sourceCode style to pre.sourceCode instead
(function() {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue;
try { var rules = sheets[i].cssRules; } catch (e) { continue; }
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
// check if there is a div.sourceCode rule
if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") continue;
var style = rule.style.cssText;
// check if color or background-color is set
if (rule.style.color === '' && rule.style.backgroundColor === '') continue;
// replace div.sourceCode by a pre.sourceCode rule
sheets[i].deleteRule(j);
sheets[i].insertRule('pre.sourceCode{' + style + '}', j);
}
}
})();
</script>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
</head>
<body>
<div class="container-fluid main-container">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Statistics Notebook</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
R Help
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="RCommands.html">R Commands</a>
</li>
<li>
<a href="RMarkdownHints.html">R Markdown Hints</a>
</li>
<li>
<a href="RCheatSheetsAndNotes.html">R Cheatsheets & Notes</a>
</li>
<li>
<a href="DataSources.html">Data Sources</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Describing Data
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="GraphicalSummaries.html">Graphical Summaries</a>
</li>
<li>
<a href="NumericalSummaries.html">Numerical Summaries</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Making Inference
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="MakingInference.html">Making Inference</a>
</li>
<li>
<a href="tTests.html">t Tests</a>
</li>
<li>
<a href="WilcoxonTests.html">Wilcoxon Tests</a>
</li>
<li>
<a href="ANOVA.html">ANOVA</a>
</li>
<li>
<a href="Kruskal.html">Kruskal-Wallis</a>
</li>
<li>
<a href="LinearRegression.html">Linear Regression</a>
</li>
<li>
<a href="LogisticRegression.html">Logistic Regression</a>
</li>
<li>
<a href="ChiSquaredTests.html">Chi Squared Tests</a>
</li>
<li>
<a href="PermutationTests.html">Randomization Testing</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Analyses
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="./Analyses/AnalysisRubric.html">Analysis Rubric</a>
</li>
<li>
<a href="./Analyses/StudentHousing.html">Good Example Analysis</a>
</li>
<li>
<a href="./Analyses/StudentHousingPOOR.html">Poor Example Analysis</a>
</li>
<li>
<a href="./Analyses/Rent.html">Rent</a>
</li>
<li>
<a href="./Analyses/Stephanie.html">Stephanie</a>
</li>
<li>
<a href="./Analyses/t Tests/HighSchoolSeniors.html">High School Seniors</a>
</li>
<li>
<a href="./Analyses/Wilcoxon Tests/RecallingWords.html">Recalling Words</a>
</li>
<li>
<a href="./Analyses/ANOVA/DayCare.html">Day Care</a>
</li>
<li>
<a href="./Analyses/Kruskal-Wallis/Food.html">Food</a>
</li>
<li>
<a href="./Analyses/Linear Regression/MySimpleLinearRegression.html">My Simple Linear Regression</a>
</li>
<li>
<a href="./Analyses/Linear Regression/CarPrices.html">Car Prices</a>
</li>
<li>
<a href="./Analyses/Logistic Regression/MyLogisticRegression.html">My Logistic Regression</a>
</li>
<li>
<a href="./Analyses/Chi Squared Tests/MyChiSquaredTest.html">My Chi-sqaured Test</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Logistic Regression</h1>
</div>
<script type="text/javascript">
function showhide(id) {
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
<hr />
<p>Regression for a qualitative binary response variable <span class="math inline">\((Y_i = 0\)</span> or <span class="math inline">\(1)\)</span>. The explanatory variables can be either quantitative or qualitative.</p>
<hr />
<div id="simple-logistic-regression-model" class="section level2 tabset tabset-pills tabset-fade">
<h2>Simple Logistic Regression Model</h2>
<div style="float:left;width:125px;" align="center">
<p><img src="Images/BinomYQuantX.png" width=58px;></p>
</div>
<p>Regression for a qualitative binary response variable <span class="math inline">\((Y_i = 0\)</span> or <span class="math inline">\(1)\)</span> using a single (typically quantitative) explanatory variable.</p>
<div id="overview" class="section level3">
<h3>Overview</h3>
<div style="padding-left:125px;">
<p>The probability that <span class="math inline">\(Y_i = 1\)</span> given the observed value of <span class="math inline">\(x_i\)</span> is called <span class="math inline">\(\pi_i\)</span> and is modeled by the equation</p>
<div style="float:right;font-size:.8em;background-color:lightgray;padding:5px;border-radius:4px;">
<a style="color:darkgray;" href="javascript:showhide('simplelogisticlatexrcode')">Math Code</a>
</div>
<div id="simplelogisticlatexrcode" style="display:none;">
<pre><code>$$
P(Y_i = 1|\, x_i) = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}} = \pi_i
$$</code></pre>
</div>
<center>
<span class="tooltipr"> <span class="math inline">\(P(\)</span> <span class="tooltiprtext">The “P” stands for “Probability that…”</span> </span><span class="tooltipr"> <span class="math inline">\(Y_i\)</span> <span class="tooltiprtext">The response variable. The “i” denotes that this is the y-value for individual “i”, where “i” is 1, 2, 3,… and so on up to <span class="math inline">\(n\)</span>, the sample size.</span> </span><span class="tooltipr"> <span class="math inline">\(= 1\)</span> <span class="tooltiprtext">Equals 1… This states that we are assuming that the probability that the response variable <span class="math inline">\(Y_i\)</span> is a 1 for the current individual.</span> </span><span class="tooltipr"> <span class="math inline">\(| x_i)\)</span> <span class="tooltiprtext">Given <span class="math inline">\(x_i\)</span>… in other words, the “|” says “given” and <span class="math inline">\(x_i\)</span> means the x-value of the current individual.</span> </span><span class="tooltipr"> <span class="math inline">\(=\)</span> <span class="tooltiprtext">Equals sign.</span> </span><span class="tooltipr"> <span class="math inline">\(\displaystyle\frac{e^{\beta_0 + \beta_1 x_i}}{1 + e^{\beta_0 + \beta_1 x_i}}\)</span> <span class="tooltiprtext">The logistic regression equation where <span class="math inline">\(e=2.71828...\)</span> is the “natural constant” number and <span class="math inline">\(\beta_0\)</span> is the y-intercept and <span class="math inline">\(\beta_1\)</span> is teh slope.</span> </span><span class="tooltipr"> <span class="math inline">\(= \pi_i\)</span> <span class="tooltiprtext">The <span class="math inline">\(\pi_i\)</span> stands for the probability of individual <span class="math inline">\(i\)</span> having a y-value equal to 1 given their <span class="math inline">\(x_i\)</span> value. It is the short hand notation for <span class="math inline">\(P(Y_i = 1 |x_i)\)</span>. (It is NOT the number 3.14…)</span> </span>
</center>
<p><br/></p>
<p>The coefficents <span class="math inline">\(\beta_0\)</span> and <span class="math inline">\(\beta_1\)</span> are difficult to interpret directly. Typicall <span class="math inline">\(e^{\beta_0}\)</span> and <span class="math inline">\(e^{\beta_1}\)</span> are interpreted instead. The value of <span class="math inline">\(e^{\beta_0}\)</span> or <span class="math inline">\(e^{\beta_1}\)</span> denotes the relative change in the odds that <span class="math inline">\(Y_i=1\)</span>. The odds that <span class="math inline">\(Y_i=1\)</span> are <span class="math inline">\(\frac{\pi_i}{1-\pi_i}\)</span>.</p>
<hr />
<p><strong>Examples:</strong> <a href="./Analyses/Logistic%20Regression/Examples/challengerLogisticReg.html">challenger</a> | <a href="./Analyses/Logistic%20Regression/Examples/mouseLogisticReg.html">mouse</a></p>
<hr />
</div>
</div>
<div id="r-instructions" class="section level3">
<h3>R Instructions</h3>
<div style="padding-left:125px;">
<p><strong>Console</strong> Help Command: <code>?glm()</code></p>
<h4 id="perform-a-logistic-regression">Perform a Logistic Regression</h4>
<a href="javascript:showhide('logistic1')">
<div class="hoverchunk">
<p><span class="tooltipr"> YourGlmName <span class="tooltiprtext">This is some name you come up with that will become the R object that stores the results of your logistic regression <code>glm()</code> command.</span> </span><span class="tooltipr"> <- <span class="tooltiprtext">This is the “left arrow” assignment operator that stores the results of your <code>glm()</code> code into <code>YourGlmName</code>.</span> </span><span class="tooltipr"> glm( <span class="tooltiprtext">glm( is an R function that stands for “General Linear Model”. It works in a similar way that the <code>lm(</code> function works except that it requires a <code>family=</code> option to be specified at the end of the command.</span> </span><span class="tooltipr"> Y <span class="tooltiprtext">Y is your binary response variable. It must consist of only 0’s and 1’s. Since TRUE’s = 1’s and FALSE’s = 0’s in R, Y could be a logical statement like (Price > 100) or (Animal == “Cat”) if your Y-variable wasn’t currently coded as 0’s and 1’s.</span> </span><span class="tooltipr"> ~ <span class="tooltiprtext">The tilde symbol ~ is used to tell R that Y should be treated as a function of the explanatory variable X.</span> </span><span class="tooltipr"> X, <span class="tooltiprtext">X is the explanatory variable (typically quantitative) that will be used to explain the probability that the response variable Y is a 1.</span> </span><span class="tooltipr"> data = NameOfYourDataset,<br />
<span class="tooltiprtext">NameOfYourDataset is the name of the dataset that contains Y and X. In other words, one column of your dataset would be called Y and another column would be called X.</span> </span><span class="tooltipr"> family=binomial) <span class="tooltiprtext">The family=binomial command tells the <code>glm(</code> function to perform a logistic regression. It turns out that <code>glm</code> can perform many different types of regressions, but we only study it as a tool to perform a logistic regression in this course.</span> </span><br/><span class="tooltipr"> summary(YourGlmName) <span class="tooltiprtext">The <code>summary</code> command allows you to print the results of your logistic regression that were previously saved in <code>YourGlmName</code>.</span> </span></p>
</div>
<p></a></p>
<div id="logistic1" style="display:none;">
<p>Example output from a regression. Hover each piece to learn more.</p>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Call:<br/> glm(formula = am ~ disp, family = binomial, data = mtcars) <span class="tooltiprouttext">This is simply a statement of your original glm(…) “call” that you made when performing your regression. It allows you to verify that you ran what you thought you ran in the glm(…).</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout"> Deviance Residuals: <span class="tooltiprouttext">Deviance residuals are a measure of how far the fitted probability for <span class="math inline">\(\pi_i\)</span> has differed from the actual outcome of <span class="math inline">\(Y_i\)</span> in terms of the log of the fitted probability space. (This is a fairly complicated idea.) </span>
</td>
</tr>
<tr>
<td align="right">
<span class="tooltiprout"> Min<br/> -1.5651 <span class="tooltiprouttext">“min” gives the value of the residual that is furthest below the regression line. Ideally, the magnitude of this value would be about equal to the magnitude of the largest positive residual (the max) because the hope is that the residuals are normally distributed around the line.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 1Q<br/> -0.6648 <span class="tooltiprouttext">“1Q” gives the first quartile of the residuals, which will always be negative, and ideally would be about equal in magnitude to the third quartile.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Median<br/> -0.2460 <span class="tooltiprouttext">“Median” gives the median of the residuals, which would ideally would be about equal to zero. Note that because the regression line is the least squares line, the mean of the residuals will ALWAYS be zero, so it is never included in the output summary. This particular median value of -0.2460 is a little smaller than zero than we would hope for and suggests a right skew in the data because the mean (0) is greater than the median (-0.2460) witnessing the residuals are right skewed. This can also be seen in the maximum being much larger in magnitude than the minimum.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 3Q<br/> 0.7276 <span class="tooltiprouttext">“3Q” gives the third quartile of the residuals, which would ideally would be about equal in magnitude to the first quartile. In this case, it is pretty close, which helps us see that the first quartile of residuals on either side of the line is behaving fairly normally.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Max</br> 2.2691 <span class="tooltiprouttext">“Max” gives the maximum positive residuals, which would ideally would be about equal in magnitude to the minimum residual. In this case, it is much larger than the minimum, which helps us see that the residuals are likely right skewed.</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout"> Coefficients: <span class="tooltiprouttext">Notice that in your glm(…) you used only <span class="math inline">\(Y\)</span> and <span class="math inline">\(X\)</span>. You did type out any coefficients, i.e., the <span class="math inline">\(\beta_0\)</span> or <span class="math inline">\(\beta_1\)</span> of the regression model. These coefficients are estimated by the glm(…) function and displayed in this part of the output along with standard errors, t-values, and p-values.</span> </span>
</td>
</tr>
<tr>
<td align="left">
</td>
<td align="right">
<span class="tooltiprout"> Estimate <span class="tooltiprouttext">To learn more about the “Estimates” of the “Coefficients” see the “Explanation” tab, “Estimating the Model Parameters” section for details.</span>
</td>
<td align="right">
<span class="tooltiprout"> Std. Error <span class="tooltiprouttext">To learn more about the “Standard Errors” of the “Coefficients” see the “Explanation” tab, “Inference for the Model Parameters” section.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> z value <span class="tooltiprouttext">The test statistic is a regular old z-score. It is most reliable when the sample size is “large.” It is a measurement of the number of standard errors the estimate is from 0.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Pr(>|z|) <span class="tooltiprouttext">This is the p-value, the probability of observing a test statistic more extreme than Z. </span> </span>
</td>
</tr>
<tr>
<td align="left">
<span class="tooltiprout"> (Intercept) <span class="tooltiprouttext">This always says “Intercept” for any glm(…) you run in R. That is because R always assumes there is a y-intercept for your regression function.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 2.630849 <span class="tooltiprouttext">This is the estimate of the y-intercept, <span class="math inline">\(\beta_0\)</span>. It is called <span class="math inline">\(b_0\)</span>. It is the value of the log of the odds that <span class="math inline">\(Y_i=1\)</span> when <span class="math inline">\(x_i\)</span> is zero. Remember to use <span class="math inline">\(e^{b_0}\)</span> to interpret this values actual effect on the odds.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 1.050170 <span class="tooltiprouttext">This is the standard error of <span class="math inline">\(b_0\)</span>. It tells you how much <span class="math inline">\(b_0\)</span> varies from sample to sample. The closer to zero, the better.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 2.505 <span class="tooltiprouttext">The test statistic for testing the hypothesis that <span class="math inline">\(\beta_0 = 0\)</span>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.01224 <span class="tooltiprouttext">This is the p-value of the test of the hypothesis that <span class="math inline">\(\beta_0 = 0\)</span>. It measures the probability of observing a z-score as extreme as the one observed. To compute it yourself in R, use <code>pnorm(-abs(your z-value))*2</code>.</span> </span>
</td>
<td align="left">
<span class="tooltiprout"> * <span class="tooltiprouttext">This is called a “star”. One star means significant at the 0.1 level of <span class="math inline">\(\alpha\)</span>.</span> </span>
</td>
</tr>
<tr>
<td align="left">
<span class="tooltiprout"> disp <span class="tooltiprouttext">This is always the name of your X-variable in your glm(Y ~ X, …).</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> -0.014604 <span class="tooltiprouttext">This is the estimate of the slope, <span class="math inline">\(\beta_1\)</span>. It is called <span class="math inline">\(b_1\)</span>. It is the change in the log of the odds that <span class="math inline">\(Y_i = 1\)</span> as X is increased by 1 unit. Remember to use <span class="math inline">\(e^{b_1}\)</span> to compute the actual effect on the odds.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.005168 <span class="tooltiprouttext">This is the standard error of <span class="math inline">\(b_1\)</span>. It tells you how much <span class="math inline">\(b_1\)</span> varies from sample to sample. The closer to zero, the better.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> -2.826 <span class="tooltiprouttext">This is the test statistic for testing the hypothesis that <span class="math inline">\(\beta_1 = 0\)</span>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.00471 <span class="tooltiprouttext">This is the p-value of the test of the hypothesis that <span class="math inline">\(\beta_1 = 0\)</span>. To compute it yourself in R, use <code>pnorm(-abs(your z-value))*2</code></span> </span>
</td>
<td align="left">
<span class="tooltiprout"> ** <span class="tooltiprouttext">This is called a “star”. Three stars means significant at the 0.001 level of <span class="math inline">\(\alpha\)</span>.</span> </span>
</td>
</tr>
</table>
<table class="rconsole">
<tr>
<td>
<span> --- </span>
</td>
</tr>
</table>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 <span class="tooltiprouttext">These “codes” explain what significance level the p-value is smaller than based on how many “stars” * the p-value is labeled with in the Coefficients table above.</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> (Dispersion parameter for binomial family taken to be 1) <span class="tooltiprouttext">This is a simplifying assumption of the logistic regression. Overdispersion is a common problem with logistic regression data, but is typically ignored. Unless you become an expert in statistics, this is not something you need to worry about.</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Null Deviance: <span class="tooltiprouttext">The deviance of the null model. This is the model that excludes any information from the x-variable, i.e., <span class="math inline">\(\beta_1=0\)</span>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 43.230 <span class="tooltiprouttext"></span> </span>
</td>
<td align="right">
<span class="tooltiprout"> on 31 degrees of freedom <span class="tooltiprouttext">The residual degrees of freedom. The higher this number, the more reliable the p-values will be from the logistic regression.</span> </span>
</td>
</tr>
</table>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Residual deviance: <span class="tooltiprouttext">The sum of log of the squared residuals. Essentially the resulting statistic of a goodness of fit test measuring how well the data works with the logistic regression model. Using pchisq(residual deviance, df residual deviance, lower.tail=FALSE) gives the p-value for this goodness of fit test. However, the residual deviance only follows a chi-squared distribution with df residual deviance when there are many repeated x-values, and all x-values have at least a few replicates.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 29.732 <span class="tooltiprouttext">This can be calculated by <code>sum(log(myglm$res^2))</code>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> on 30 degrees of freedom <span class="tooltiprouttext">This is <span class="math inline">\(n-p\)</span> where <span class="math inline">\(n\)</span> is the sample size and <span class="math inline">\(p\)</span> is the number of parameters in the regression model. In this case, there is a sample size of 32 and two parameters, <span class="math inline">\(\beta_0\)</span> and <span class="math inline">\(\beta_1\)</span>, so 32-2 = 30.</span> </span>
</td>
</tr>
</table>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> AIC: <span class="tooltiprouttext">As stated in the R Help file for ?glm, “A version of Akaike’s An Information Criterion…” The AIC is useful for comparing different models for the same Y-variable. The glm model with the lowest AIC (which can go negative) is the best model.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 33.732 <span class="tooltiprouttext">The AIC for this particular model is 33.732. So if a different model (using the same Y-variable as this model) can get a lower AIC, it is a better model.</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Number of Fisher Scoring iterations: <span class="tooltiprouttext">If you have taken a class in Numerical Analysis, this tells you how many iterations of the maximization algorithm were required before converging to the “Estimates” of the parameters <span class="math inline">\(\beta_0\)</span> and <span class="math inline">\(\beta_1\)</span> found in the summary.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 5 <span class="tooltiprouttext">This implementation of glm required 5 Fisher Scoring iterations to converge. Fewer iterations hints that the model is a better fit than when many iterations are required.</span> </span>
</td>
</tr>
</table>
</div>
<p><br/></p>
<h4 id="diagnose-the-goodness-of-fit">Diagnose the Goodness-of-Fit</h4>
<p>There are two ways to check the <strong>goodness of fit</strong> of a logistic regression model.</p>
<div style="padding-left:25px;">
<p><strong>Option 1</strong>: Hosmer-Lemeshow Goodness-of-Fit Test</p>
<p>To check the <strong>goodness of fit</strong> of a logistic regression model where there are <strong>few or no replicated <span class="math inline">\(x\)</span>-values</strong> use the Hosmer-Lemeshow Test.</p>
<a href="javascript:showhide('goodnessoffit2')">
<div class="hoverchunk">
<p><span class="tooltipr"> library(ResourceSelection) <span class="tooltiprtext">This loads the ResourceSelection R package so that you can access the hoslem.test() function. You may need to run the code: install.packages(“ResourceSelection”) first.</span> </span><br/><span class="tooltipr"> hoslem.test( <span class="tooltiprtext">This R function performs the Hosmer-Lemeshow Goodness of Fit Test. See the “Explanation” file to learn about this test.</span> </span><span class="tooltipr"> YourGlmName <span class="tooltiprtext"><code>YourGlmName</code> is the name of your glm(…) code that you created previously.</span> </span><span class="tooltipr"> $y, <span class="tooltiprtext">ALWAYS type a “y” here. This gives you the actual binary (0,1) y-values of your logistic regression. The goodness of fit test will compare these actual values to your predicted probabilities for each value in order to see if the model is a “good fit.”</span> </span><span class="tooltipr"> YourGlmName <span class="tooltiprtext"><code>YourGlmName</code> is the name you used to save the results of your glm(…) code.</span> </span><span class="tooltipr"> $fitted, <span class="tooltiprtext">ALWAYS type “fitted” here. This gives you the fitted probabilities <span class="math inline">\(\pi_i\)</span> of your logistic regression.</span> </span><span class="tooltipr"> g=10) <span class="tooltiprtext">The “g=10” is the default option for the value of g. The g is the number of groups to run the goodness of fit test on. Just leave it at 10 unless you are told to do otherwise. Ask your teacher for more information if you are interested.</span> </span></p>
</div>
<p></a></p>
<div id="goodnessoffit2" style="display:none;">
<pre><code>##
## Hosmer and Lemeshow goodness of fit (GOF) test
##
## data: myglm$y, myglm$fitted
## X-squared = 5.7327, df = 8, p-value = 0.6771</code></pre>
<p>Note that the null hypothesis of the goodness-of-fit test is that “the logistic regression is a good fit.” So we actually don’t want to “reject the null” in this case. So a large p-value here means our logistic regression fits the data satisfactorily. A small p-value implies a poor fit and the results of the logistic regression should not be fully trusted.</p>
</div>
<p><br/></p>
<p><strong>Option 2</strong>: Deviance Goodness-of-fit Test</p>
<p>In some cases, there are <strong>many replicated <span class="math inline">\(x\)</span>-values</strong> for <strong>all</strong> x-values. Though this is rare, it is good to use the <em>deviance goodness-of-fit test</em> whenever this happens.</p>
<a href="javascript:showhide('goodnessoffit1')">
<div class="hoverchunk">
<p><span class="tooltipr"> pchisq( <span class="tooltiprtext">The <code>pchisq</code> command allows you to compute p-values from the chi-squared distribution.</span> </span><span class="tooltipr"> residual deviance, <span class="tooltiprtext">The residual deviance is shown at the bottom of the output of your <code>summary(YourGlmName)</code> and should be typed in here as a number like 25.3.</span> </span><span class="tooltipr"> df for residual deviance, <span class="tooltiprtext">The df for the residual deviance is also shown at the bottom of the output of your <code>summary(YourGlmName)</code>.</span> </span><span class="tooltipr"> lower.tail=FALSE) <span class="tooltiprtext">This command ensures you find the probability of the chi-squared distribution being as extreme or more extreme than the observed value of residual deviance.</span> </span></p>
</div>
<p></a></p>
<div id="goodnessoffit1" style="display:none;">
<pre><code>##
## Call:
## glm(formula = am ~ disp, family = binomial, data = mtcars)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.5651 -0.6648 -0.2460 0.7276 2.2691
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 2.630849 1.050170 2.505 0.01224 *
## disp -0.014604 0.005168 -2.826 0.00471 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 43.230 on 31 degrees of freedom
## Residual deviance: 29.732 on 30 degrees of freedom
## AIC: 33.732
##
## Number of Fisher Scoring iterations: 5</code></pre>
<pre><code>## [1] 0.479439</code></pre>
<p>The null hypothesis of the goodness-of-fit test is that the logistic regression is a good fit of the data. So a large p-value (like 0.479) is good because it allows us to trust the results of our logistic regression. When the p-value becomes very small, we must “reject the null” and conclude a poor fit, which implies that we should not trust the results of the logistic regression.</p>
</div>
</div>
<p><br/></p>
<h4 id="plot-the-regression">Plot the Regression</h4>
<div class="tab">
<p><button class="tablinks" onclick="openTab(event, 'LogisticBaseplot')">Base R</button> <button class="tablinks" onclick="openTab(event, 'Logisticggplot')">ggplot2</button></p>
</div>
<div id="LogisticBaseplot" class="tabcontent">
<p>
<a href="javascript:showhide('LogisticBaseplot2')">
<div class="hoverchunk">
<p><span class="tooltipr"> plot( <span class="tooltiprtext">The plot function allows us to draw a scatterplot where the y-axis is only 0’s or 1’s and the x-axis is quantitative.</span> </span><span class="tooltipr"> Y <span class="tooltiprtext">Y should be some logical statement like Fail > 0 or sex == “B” or height < 68. In other words, Y needs to be a collection of 0’s and 1’s.</span> </span><span class="tooltipr"> ~ <span class="tooltiprtext">The tilde is read “Y on X.”</span> </span><span class="tooltipr"> X, <span class="tooltiprtext">X is some quantitative variable.</span> </span><span class="tooltipr"> data= <span class="tooltiprtext">Tell the plot which data set to use. X and Y are columns of that data set.</span> </span><span class="tooltipr"> YourDataSet <span class="tooltiprtext">The name of your data set.</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis for plot(…) function.</span> </span><br/><span class="tooltipr"> curve( <span class="tooltiprtext">A function in R that draws a “curve” on a plot. Using add=TRUE puts the curve onto the current plot.</span> </span><span class="tooltipr"> exp( <span class="tooltiprtext">This allows you to compute e to the power of something. So exp(1) = e, exp(2) = e^2 and so on.</span> </span><span class="tooltipr"> <span class="math inline">\(b_0\)</span> + <span class="tooltiprtext">This is the “Intercept” estimate from your logistic regression summary output.</span> </span><span class="tooltipr"> <span class="math inline">\(b_1\)</span> <span class="tooltiprtext">This is the slope estimate from your logistic regression summary output.</span> </span><span class="tooltipr"> *x <span class="tooltiprtext">The curve function demands you ALWAYS use a lower-case “x” in this function.</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis.</span> </span><span class="tooltipr"> / <span class="tooltiprtext">The division symbol.</span> </span><span class="tooltipr"> (1 + <span class="tooltiprtext">Required for the formula.</span> </span><span class="tooltipr"> exp(<span class="math inline">\(b_0\)</span> + <span class="math inline">\(b_1\)</span>*x) <span class="tooltiprtext">This needs to match exactly the first version of this statement.</span> </span><span class="tooltipr"> ), <span class="tooltiprtext">Closing parenthesis for the denominator.</span> </span><span class="tooltipr"> add = TRUE) <span class="tooltiprtext">This makes the curve be added to the current plot. If it is left out, the curve will be drawn in a new plot.</span> </span></p>
</div>
<p></a></p>
<div id="LogisticBaseplot2" style="display:none;">
<p><img src="LogisticRegression_files/figure-html/unnamed-chunk-4-1.png" width="672" /></p>
</div>
</p>
</div>
<div id="Logisticggplot" class="tabcontent">
<p>
<a href="javascript:showhide('Logisticggplot2')">
<div class="hoverchunk">
<p><span class="tooltipr"> ggplot( <span class="tooltiprtext">The ggplot(…) function is used to create a basic ggplot frame.</span> </span><span class="tooltipr"> data=YourDataSetName, <span class="tooltiprtext">Use this to specify the name of your data set.</span> </span><span class="tooltipr"> aes( <span class="tooltiprtext">The aes(…) function stands for “aesthetics” and tells the ggplot which variables to match up with the x-axis and y-axis of the graph as well as other visual things like the type of plotting characters, size of plotting characters, color, fill, and so on.</span> </span><span class="tooltipr"> x=X, <span class="tooltiprtext">Use x=nameOfYourXvariable to declare the x-axis of your graph.</span> </span><span class="tooltipr"> y=Y <span class="tooltiprtext">Use y=nameOfYourYvariable to declare the y-axis of your graph. If your y-variable is a logical expression, like height>60 then you must use y=as.numeric(height>60).</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis for aes(…) function.</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis for ggplot(…) function.</span> </span><span class="tooltipr"> + <span class="tooltiprtext">The plus sign adds a new layer to the ggplot.</span> </span><br/><span class="tooltipr"> geom_point( <span class="tooltiprtext">Tells the plot to add the physical geometry of “points” to the plot.</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis for the geom_point() function.</span> </span><span class="tooltipr"> + <span class="tooltiprtext">Add another layer to the plot.</span> </span><br/><span class="tooltipr"> geom_smooth( <span class="tooltiprtext">Add a smoothing line to the graph.</span> </span><span class="tooltipr"> method=“glm”, <span class="tooltiprtext">This adds a general linear model to the graph.</span> </span><span class="tooltipr"> method.args = list(family=“binomial”), <span class="tooltiprtext">This tells the method=“glm” to choose specifically the “binomial” model, otherwise known as the “logistic regression” model.</span> </span><span class="tooltipr"> se=FALSE <span class="tooltiprtext">Turn off the displaying of the confidence band around the logistic regression. You can turn this on if you know what it means.</span> </span><span class="tooltipr"> ) <span class="tooltiprtext">Closing parenthesis for the geom_smooth() function.</span> </span><span class="tooltipr"> + <span class="tooltiprtext">Add another layer to the ggplot.</span> </span><br/><span class="tooltipr"> theme_bw() <span class="tooltiprtext">Give the graph a basic black and white theme. Other themes are possible, see ?theme_ in your Console.</span> </span></p>
</div>
<p></a></p>
<div id="Logisticggplot2" style="display:none;">
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="LogisticRegression_files/figure-html/unnamed-chunk-5-1.png" width="672" /></p>
</div>
</p>
</div>
<p><br/></p>
<h4 id="predict-probabilities">Predict Probabilities</h4>
<p>To predict the probability that <span class="math inline">\(Y_i=1\)</span> for a given <span class="math inline">\(x\)</span>-value, use the code</p>
<a href="javascript:showhide('LogisticPredict')">
<div class="hoverchunk">
<p><span class="tooltipr"> predict( <span class="tooltiprtext">The predict() function allows us to use the regression model that was obtained from glm() to predict the probability that <span class="math inline">\(Y_i = 1\)</span> for a given <span class="math inline">\(X_i\)</span>.</span> </span><span class="tooltipr"> YourGlmName, <span class="tooltiprtext"><code>YourGlmName</code> is the name of the object you created when you performed your logistic regression using glm().</span> </span><span class="tooltipr"> newdata = <span class="tooltiprtext">The <code>newdata =</code> command allows you to specify the x-values for which you want to obtain predicted probabilities that <span class="math inline">\(Y_i=1\)</span>.</span> </span><span class="tooltipr"> data.frame(xVariableName = someNumericValue), <span class="tooltiprtext">The xVariableName is the same one you used in your glm(y ~ x, …) statement for “x”. Input any desired value for the “someNumericValue” spot. Then, the predict code uses the logistic regression model equation to calculate a predicted probability that <span class="math inline">\(Y_i = 1\)</span> for the given <span class="math inline">\(x_i\)</span> value that you specify.</span> </span><span class="tooltipr"> type = “response”) <span class="tooltiprtext">The type = “response” options specifies that you want predicted probabilities. There are other options available. See ?predict.glm for details.</span> </span></p>
</div>
<p></a></p>
<div id="LogisticPredict" style="display:none;">
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1"></a>myglm <-<span class="st"> </span><span class="kw">glm</span>(am <span class="op">~</span><span class="st"> </span>disp, <span class="dt">data =</span> mtcars, <span class="dt">family =</span> binomial)</span>
<span id="cb6-2"><a href="#cb6-2"></a><span class="kw">predict</span>(myglm, <span class="dt">newdata =</span> <span class="kw">data.frame</span>(<span class="dt">disp =</span> <span class="dv">200</span>), <span class="dt">type =</span> <span class="st">"response"</span>)</span></code></pre></div>
<pre><code>## 1
## 0.4280016</code></pre>
</div>
<hr />
</div>
</div>
<div id="explanation" class="section level3">
<h3>Explanation</h3>
<div style="padding-left:125px;">
<p>Simple Logistic Regression is used when</p>
<ul>
<li>the response variable is binary <span class="math inline">\((Y_i=0\)</span> or <span class="math inline">\(1)\)</span>, and</li>
<li>there is a single explanatory variable <span class="math inline">\(X\)</span> that is typically quantitative but could be qualitative (if <span class="math inline">\(X\)</span> is binary or ordinal).</li>
</ul>
<h4 id="the-model">The Model</h4>
<p>Since <span class="math inline">\(Y_i\)</span> is binary (can only be 0 or 1) the model focuses on describing the probability that <span class="math inline">\(Y_i=1\)</span> for a given scenario. The probability that <span class="math inline">\(Y_i = 1\)</span> given the observed value of <span class="math inline">\(x_i\)</span> is called <span class="math inline">\(\pi_i\)</span> and is modeled by the equation</p>
<p><span class="math display">\[
P(Y_i = 1|\, x_i) = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}} = \pi_i
\]</span></p>
<p>The assumption is that for certain values of <span class="math inline">\(X\)</span> the probability that <span class="math inline">\(Y_i=1\)</span> is higher than for other values of <span class="math inline">\(X\)</span>.</p>
<h4 id="interpretation">Interpretation</h4>
<p>This model for <span class="math inline">\(\pi_i\)</span> comes from modeling the <em>log of the odds</em> that <span class="math inline">\(Y_i=1\)</span> using a linear regression, i.e., <span class="math display">\[
\log\underbrace{\left(\frac{\pi_i}{1-\pi_i}\right)}_{\text{Odds for}\ Y_i=1} = \underbrace{\beta_0 + \beta_1 x_i}_{\text{linear regression}}
\]</span> Beginning to solve this equation for <span class="math inline">\(\pi_i\)</span> leads to the intermediate, but important result that <span class="math display">\[
\underbrace{\frac{\pi_i}{1-\pi_i}}_{\text{Odds for}\ Y_i=1} = e^{\overbrace{\beta_0 + \beta_1 x_i}^{\text{linear regression}}} = e^{\beta_0}e^{\beta_1 x_i}
\]</span> Thus, while the coefficients <span class="math inline">\(\beta_0\)</span> and <span class="math inline">\(\beta_1\)</span> are difficult to interpret directly, <span class="math inline">\(e^{\beta_0}\)</span> and <span class="math inline">\(e^{\beta_1}\)</span> have a valuable interpretation. The value of <span class="math inline">\(e^{\beta_0}\)</span> is interpreted as the odds for <span class="math inline">\(Y_i=1\)</span> when <span class="math inline">\(x_i = 0\)</span>. It may not be possible for a given model to have <span class="math inline">\(x_i=0\)</span>, in which case <span class="math inline">\(e^{\beta_0}\)</span> has no interpretation. The value of <span class="math inline">\(e^{\beta_1}\)</span> denotes the proportional change in the odds that <span class="math inline">\(Y_i=1\)</span> for every one unit increase in <span class="math inline">\(x_i\)</span>.</p>
<p>Notice that solving the last equation for <span class="math inline">\(\pi_i\)</span> results in the logistic regression model presented at the beginning of this page.</p>
<h4 id="hypothesis-testing">Hypothesis Testing</h4>
<p>Similar to linear regression, the hypothesis that <span class="math display">\[
H_0: \beta_1 = 0 \\
H_a: \beta_1 \neq 0
\]</span> can be tested with a logistic regression. If <span class="math inline">\(\beta_1 = 0\)</span>, then there is no relationship between <span class="math inline">\(x_i\)</span> and the log of the odds that <span class="math inline">\(Y_i = 1\)</span>. In other words, <span class="math inline">\(x_i\)</span> is not useful in predicting the probability that <span class="math inline">\(Y_i = 1\)</span>. If <span class="math inline">\(\beta_1 \neq 0\)</span>, then there is information in <span class="math inline">\(x_i\)</span> that can be utilized to predict the probability that <span class="math inline">\(Y_i = 1\)</span>, i.e., the logistic regression is meaningful.</p>
<h4 id="diagnostics">Checking Model Assumptions</h4>
<p>The model assumptions are not as clear in logistic regression as they are in linear regression. For our purposes we will focus only on considering the goodness of fit of the logistic regression model. If the model appears to fit the data well, then it will be assumed to be appropriate.</p>
<div style="padding-left:15px;">
<h5 id="deviance-goodness-of-fit-test">Deviance Goodness of Fit Test</h5>
<p>If there are replicated values of each <span class="math inline">\(x_i\)</span>, then the deviance goodness of fit test tests the hypotheses <span class="math display">\[
H_0: \pi_i = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}}
\]</span> <span class="math display">\[
H_a: \pi_i \neq \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}}
\]</span></p>
<h5 id="hosmer-lemeshow-goodness-of-fit-test">Hosmer-Lemeshow Goodness of Fit Test</h5>
<p>If there are very few or no replicated values of each <span class="math inline">\(x_i\)</span>, then the Hosmer-Lemeshow goodness of fit test can be used to test these same hypotheses. In each case, the null assumes that logistic regression is a good fit for the data while the alternative is that logistic regression is not a good fit.</p>
</div>
<h4 id="prediction">Prediction</h4>
<p>One of the great uses of Logistic Regression is that it provides an estimate of the probability that <span class="math inline">\(Y_i=1\)</span> for a given value of <span class="math inline">\(x_i\)</span>. This probability is often referred to as the <em>risk</em> that <span class="math inline">\(Y_i=1\)</span> for a certain individual. For example, if <span class="math inline">\(Y_i=1\)</span> implies a person has a disease, then <span class="math inline">\(\pi_i=P(Y_i=1)\)</span> represents the risk of individual <span class="math inline">\(i\)</span> having the disease based on their value of <span class="math inline">\(x_i\)</span>, perhaps a measure of their cholesterol or some other predictor of the disease.</p>
</div>
<hr />
</div>
<div id="section" class="section level3">
<h3></h3>
<hr />
</div>
</div>
<div id="multiple-logistic-regression-model" class="section level2 tabset tabset-pills tabset-fade">
<h2>Multiple Logistic Regression Model</h2>
<div style="float:left;width:125px;" align="center">
<p><img src="Images/BinomYMultX.png" width=98px;></p>
</div>
<p>Logistic regression for multiple explanatory variables that can either be quantitative or qualitative or a mixture of the two.</p>
<div id="overview-1" class="section level3">
<h3>Overview</h3>
<div style="padding-left:125px;">
<p>The probability that <span class="math inline">\(Y_i = 1\)</span> given the observed data <span class="math inline">\((x_{i1},\ldots,x_{ip})\)</span> is called <span class="math inline">\(\pi_i\)</span> and is modeled by the equation</p>
<p><span class="math display">\[
P(Y_i = 1|\, x_{i1},\ldots,x_{ip}) = \frac{e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip}}}{1+e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip} }} = \pi_i
\]</span></p>
<p>The coefficents <span class="math inline">\(\beta_0,\beta_1,\ldots,\beta_p\)</span> are difficult to interpret directly. Typically <span class="math inline">\(e^{\beta_k}\)</span> for <span class="math inline">\(k=0,1,\ldots,p\)</span> is interpreted instead. The value of <span class="math inline">\(e^{\beta_k}\)</span> denotes the relative change in the odds that <span class="math inline">\(Y_i=1\)</span>. The odds that <span class="math inline">\(Y_i=1\)</span> are <span class="math inline">\(\frac{\pi_i}{1-\pi_i}\)</span>.</p>
<hr />
<p><strong>Examples:</strong> <a href="./Analyses/Logistic%20Regression/Examples/GSSMultipleLogisticReg.html">GSS</a></p>
<hr />
</div>
</div>
<div id="r-instructions-1" class="section level3">
<h3>R Instructions</h3>
<div style="padding-left:125px;">
<p><strong>Console</strong> Help Command: <code>?glm()</code></p>
<h4 id="perform-the-logistic-regression">Perform the Logistic Regression</h4>
<p>To perform a logistic regression in R use the commands</p>
<a href="javascript:showhide('logistic2')">
<div class="hoverchunk">
<p><span class="tooltipr"> YourGlmName <span class="tooltiprtext">This is some name you come up with that will become the R object that stores the results of your logistic regression <code>glm()</code> command.</span> </span><span class="tooltipr"> <- <span class="tooltiprtext">This is the “left arrow” assignment operator that stores the results of your <code>glm()</code> code into <code>YourGlmName</code>.</span> </span><span class="tooltipr"> glm( <span class="tooltiprtext">glm( is an R function that stands for “General Linear Model”. It works in a similar way that the <code>lm(</code> function works except that it requires a <code>family=</code> option to be specified at the end of the command.</span> </span><span class="tooltipr"> Y <span class="tooltiprtext">Y is your binary response variable. It must consist of only 0’s and 1’s. Since TRUE’s = 1’s and FALSE’s = 0’s in R, Y could be a logical statement like (Price > 100) or (Animal == “Cat”) if your Y-variable wasn’t currently coded as 0’s and 1’s.</span> </span><span class="tooltipr"> ~ <span class="tooltiprtext">The tilde symbol ~ is used to tell R that Y should be treated as a function of the explanatory variable X.</span> </span><span class="tooltipr"> X1 <span class="tooltiprtext">X1 is the first explanatory variable (typically quantitative) that will be used to explain the probability that the response variable Y is a 1.</span> </span><span class="tooltipr"> * <span class="tooltiprtext">The times symbol allows a shortcut for writing X1 + X2 + X1:X2 = X1*X2.</span> </span><span class="tooltipr"> X2 <span class="tooltiprtext">X2 is second the explanatory variable either quantitative or qualitative that will be used to explain the probability that the response variable Y is a 1.</span> </span><span class="tooltipr"> …, <span class="tooltiprtext">In theory, you could have many other explanatory variables, interaction terms, or even squared, cubed, or other transformations of terms added to this model.</span> </span><span class="tooltipr"> data = NameOfYourDataset,<br />
<span class="tooltiprtext">NameOfYourDataset is the name of the dataset that contains Y and X. In other words, one column of your dataset would be called Y and another column would be called X.</span> </span><span class="tooltipr"> family=binomial) <span class="tooltiprtext">The family=binomial command tells the <code>glm(</code> function to perform a logistic regression. It turns out that <code>glm</code> can perform many different types of regressions, but we only study it as a tool to perform a logistic regression in this course.</span> </span><br/><span class="tooltipr"> summary(YourGlmName) <span class="tooltiprtext">The <code>summary</code> command allows you to print the results of your logistic regression that were previously saved in <code>YourGlmName</code>.</span> </span></p>
</div>
<p></a></p>
<div id="logistic2" style="display:none;">
<p>Example output from a regression. Hover each piece to learn more.</p>
<table class="rconsole">
<tr>
<td>
<span class="tooltiprout"> Call:<br/> glm(formula = weight > 100 ~ Time*Diet, family = binomial, data = ChickWeight) <span class="tooltiprouttext">This is simply a statement of your original glm(…) “call” that you made when performing your regression. It allows you to verify that you ran what you thought you ran in the glm(…).</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout"> Deviance Residuals: <span class="tooltiprouttext">Deviance residuals are a measure of how far the fitted probability for <span class="math inline">\(\pi_i\)</span> has differed from the actual outcome of <span class="math inline">\(Y_i\)</span> in terms of the log of the fitted probability space. (This is a fairly complicated idea.) </span>
</td>
</tr>
<tr>
<td align="right">
<span class="tooltiprout"> Min<br/> -2.9446 <span class="tooltiprouttext">“min” gives the value of the residual that is furthest below the regression line. Ideally, the magnitude of this value would be about equal to the magnitude of the largest positive residual (the max) because the hope is that the residuals are normally distributed around the line.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 1Q<br/> -0.2364 <span class="tooltiprouttext">“1Q” gives the first quartile of the residuals, which will always be negative, and ideally would be about equal in magnitude to the third quartile.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Median<br/> 0.0000 <span class="tooltiprouttext">“Median” gives the median of the residuals, which would ideally would be about equal to zero. Note that because the regression line is the least squares line, the mean of the residuals will ALWAYS be zero, so it is never included in the output summary.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 3Q<br/> 0.2776 <span class="tooltiprouttext">“3Q” gives the third quartile of the residuals, which would ideally would be about equal in magnitude to the first quartile. In this case, it is pretty close, which helps us see that the first quartile of residuals on either side of the line is behaving fairly normally.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Max</br> 1.9968 <span class="tooltiprouttext">“Max” gives the maximum positive residuals, which would ideally would be about equal in magnitude to the minimum residual. In this case, it is much larger than the minimum, which helps us see that the residuals are likely right skewed.</span> </span>
</td>
</tr>
</table>
<p><br/></p>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout"> Coefficients: <span class="tooltiprouttext">Notice that in your glm(…) you used only <span class="math inline">\(Y\)</span> and <span class="math inline">\(X\)</span>. You did type out any coefficients, i.e., the <span class="math inline">\(\beta_0\)</span> or <span class="math inline">\(\beta_1\)</span> of the regression model. These coefficients are estimated by the glm(…) function and displayed in this part of the output along with standard errors, t-values, and p-values.</span> </span>
</td>
</tr>
<tr>
<td align="left">
</td>
<td align="right">
<span class="tooltiprout"> Estimate <span class="tooltiprouttext">To learn more about the “Estimates” of the “Coefficients” see the “Explanation” tab, “Estimating the Model Parameters” section for details.</span>
</td>
<td align="right">
<span class="tooltiprout"> Std. Error <span class="tooltiprouttext">To learn more about the “Standard Errors” of the “Coefficients” see the “Explanation” tab, “Inference for the Model Parameters” section.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> z value <span class="tooltiprouttext">The Z-score testing the hypothesis that <span class="math inline">\(\beta_j=0\)</span></span> </span>
</td>
<td align="right">
<span class="tooltiprout"> Pr(>|z|) <span class="tooltiprouttext">The p-value for the corresponding Z-score.</span> </span>
</td>
</tr>
<tr>
<td align="left">
<span class="tooltiprout"> (Intercept) <span class="tooltiprouttext">This always says “Intercept” for any glm(…) you run in R. That is because R always assumes there is a y-intercept for your regression function.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> -4.97603 <span class="tooltiprouttext">This is the estimate of the y-intercept, <span class="math inline">\(\beta_0\)</span>. It is called <span class="math inline">\(b_0\)</span>. It is the average y-value when X is zero.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.65316 <span class="tooltiprouttext">This is the standard error of <span class="math inline">\(b_0\)</span>. It tells you how much <span class="math inline">\(b_0\)</span> varies from sample to sample. The closer to zero, the better.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> -7.618 <span class="tooltiprouttext">Z-score for <span class="math inline">\(b_0\)</span>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 2.57e-14 <span class="tooltiprouttext">This is the p-value of the test of the hypothesis that <span class="math inline">\(\beta_0 = 0\)</span>. It measures the probability of observing a Z-value as extreme as the one observed. To compute it yourself in R, use <code>pnorm(-abs(your z-value))*2</code>.</span> </span>
</td>
<td align="left">
<span class="tooltiprout"> *** <span class="tooltiprouttext">This is called a “star”. Three stars means significant at the 0.01 level of <span class="math inline">\(\alpha\)</span>.</span> </span>
</td>
</tr>
<tr>
<td align="left">
<span class="tooltiprout"> Time <span class="tooltiprouttext">This is always the name of your X-variable in your glm(Y ~ X, …).</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.39111 <span class="tooltiprouttext">This is the estimate of the slope, <span class="math inline">\(\beta_1\)</span>. It is called <span class="math inline">\(b_1\)</span>. It is the change in the average y-value as X is increased by 1 unit.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 0.04979 <span class="tooltiprouttext">This is the standard error of <span class="math inline">\(b_1\)</span>. It tells you how much <span class="math inline">\(b_1\)</span> varies from sample to sample. The closer to zero, the better.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 7.854 <span class="tooltiprouttext">Z-score for <span class="math inline">\(b_1\)</span>.</span> </span>
</td>
<td align="right">
<span class="tooltiprout"> 4.02e-15 <span class="tooltiprouttext">This is the p-value of the test of the hypothesis that <span class="math inline">\(\beta_1 = 0\)</span>. To compute it yourself in R, use <code>pt(-abs(your t-value), df of your regression)*2</code></span> </span>
</td>
<td align="left">
<span class="tooltiprout"> *** <span class="tooltiprouttext">This is called a “star”. Three stars means significant at the 0.01 level of <span class="math inline">\(\alpha\)</span>.</span> </span>
</td>
</tr>
<tr>
<td align="left">
<span class="tooltiprout"> Diet2 <span class="tooltiprouttext">This is always the name of your X-variable in your glm(Y ~ X, …).</span> </span>
</td>
<td align="right">