forked from saundersg/Statistics-Notebook
-
Notifications
You must be signed in to change notification settings - Fork 3
/
LogisticRegression.Rmd
1718 lines (1476 loc) · 71.3 KB
/
LogisticRegression.Rmd
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
---
title: "Logistic Regression"
---
<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>
```{r, include=FALSE}
library(plotly)
library(ResourceSelection)
```
----
Regression for a qualitative binary response variable $(Y_i = 0$ or $1)$. The explanatory variables can be either quantitative or qualitative.
----
## Simple Logistic Regression Model {.tabset .tabset-pills .tabset-fade}
<div style="float:left;width:125px;" align=center>
<img src="./Images/BinomYQuantX.png" width=58px;>
</div>
Regression for a qualitative binary response variable $(Y_i = 0$ or $1)$ using a single (typically quantitative) explanatory variable.
### Overview
<div style="padding-left:125px;">
The probability that $Y_i = 1$ given the observed value of $x_i$ is called $\pi_i$ and is modeled by the equation
<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;">
```{}
$$
P(Y_i = 1|\, x_i) = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}} = \pi_i
$$
```
</div>
<center>
<span class="tooltipr">
$P($
<span class="tooltiprtext">The "P" stands for "Probability that..."</span>
</span><span class="tooltipr">
$Y_i$
<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 $n$, the sample size.</span>
</span><span class="tooltipr">
$= 1$
<span class="tooltiprtext">Equals 1... This states that we are assuming that the probability that the response variable $Y_i$ is a 1 for the current individual.</span>
</span><span class="tooltipr">
$| x_i)$
<span class="tooltiprtext">Given $x_i$... in other words, the "|" says "given" and $x_i$ means the x-value of the current individual.</span>
</span><span class="tooltipr">
$=$
<span class="tooltiprtext">Equals sign.</span>
</span><span class="tooltipr">
$\displaystyle\frac{e^{\beta_0 + \beta_1 x_i}}{1 + e^{\beta_0 + \beta_1 x_i}}$
<span class="tooltiprtext">The logistic regression equation where $e=2.71828...$ is the "natural constant" number and $\beta_0$ is the y-intercept and $\beta_1$ is teh slope.</span>
</span><span class="tooltipr">
$= \pi_i$
<span class="tooltiprtext">The $\pi_i$ stands for the probability of individual $i$ having a y-value equal to 1 given their $x_i$ value. It is the short hand notation for $P(Y_i = 1 |x_i)$. (It is NOT the number 3.14...)</span>
</span>
</center>
<br/>
The coefficents $\beta_0$ and $\beta_1$ are difficult to interpret directly. Typicall $e^{\beta_0}$ and $e^{\beta_1}$ are interpreted instead. The value of $e^{\beta_0}$ or $e^{\beta_1}$ denotes the relative change in the odds that $Y_i=1$. The odds that $Y_i=1$ are $\frac{\pi_i}{1-\pi_i}$.
----
**Examples:** [challenger](./Analyses/Logistic Regression/Examples/challengerLogisticReg.html) | [mouse](./Analyses/Logistic Regression/Examples/mouseLogisticReg.html)
----
</div>
### R Instructions
<div style="padding-left:125px;">
**Console** Help Command: `?glm()`
#### Perform a Logistic Regression
<a href="javascript:showhide('logistic1')">
<div class="hoverchunk">
<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 `glm()` command.</span>
</span><span class="tooltipr">
<-
<span class="tooltiprtext">This is the "left arrow" assignment operator that stores the results of your `glm()` code into `YourGlmName`.</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 `lm(` function works except that it requires a `family=` 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,
<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 `glm(` function to perform a logistic regression. It turns out that `glm` 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 `summary` command allows you to print the results of your logistic regression that were previously saved in `YourGlmName`.</span>
</span>
</div>
</a>
<div id="logistic1" style="display:none;">
Example output from a regression. Hover each piece to learn more.
<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>
<br/>
<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 $\pi_i$ has differed from the actual outcome of $Y_i$ 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>
<br/>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout">
Coefficients:
<span class="tooltiprouttext">Notice that in your glm(...) you used only $Y$ and $X$. You did type out any coefficients, i.e., the $\beta_0$ or $\beta_1$ 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, $\beta_0$. It is called $b_0$. It is the value of the log of the odds that $Y_i=1$ when $x_i$ is zero. Remember to use $e^{b_0}$ 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 $b_0$. It tells you how much $b_0$ 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 $\beta_0 = 0$.</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 $\beta_0 = 0$. It measures the probability of observing a z-score as extreme as the one observed. To compute it yourself in R, use `pnorm(-abs(your z-value))*2`.</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 $\alpha$.</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, $\beta_1$. It is called $b_1$. It is the change in the log of the odds that $Y_i = 1$ as X is increased by 1 unit. Remember to use $e^{b_1}$ 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 $b_1$. It tells you how much $b_1$ 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 $\beta_1 = 0$.</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 $\beta_1 = 0$. To compute it yourself in R, use `pnorm(-abs(your z-value))*2`</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 $\alpha$.</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>
<br/>
<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>
<br/>
<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., $\beta_1=0$.</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 `sum(log(myglm$res^2))`.</span>
</span>
</td><td align="right">
<span class="tooltiprout">
on 30 degrees of freedom
<span class="tooltiprouttext">This is $n-p$ where $n$ is the sample size and $p$ is the number of parameters in the regression model. In this case, there is a sample size of 32 and two parameters, $\beta_0$ and $\beta_1$, 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>
<br/>
<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 $\beta_0$ and $\beta_1$ 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>
<br/>
#### Diagnose the Goodness-of-Fit
There are two ways to check the **goodness of fit** of a logistic regression model.
<div style="padding-left:25px;">
**Option 1**: Hosmer-Lemeshow Goodness-of-Fit Test (Most Common)
To check the **goodness of fit** of a logistic regression model where there are **few or no replicated $x$-values** use the Hosmer-Lemeshow Test.
<a href="javascript:showhide('goodnessoffit2')">
<div class="hoverchunk">
<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">`YourGlmName` 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">`YourGlmName` 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 $\pi_i$ 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>
</div>
</a>
<div id="goodnessoffit2" style="display:none;">
```{r, echo=FALSE}
myglm <- glm(am ~ disp, data = mtcars, family = binomial)
library(ResourceSelection)
hoslem.test(myglm$y, myglm$fitted)
```
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.
</div>
<br/>
**Option 2**: Deviance Goodness-of-fit Test (Less Common)
In some cases, there are **many replicated $x$-values** for **all** x-values, i.e., each value of x is repeated more than 50 times. Though this is rare, it is good to use the *deviance goodness-of-fit test* whenever this happens.
<a href="javascript:showhide('goodnessoffit1')">
<div class="hoverchunk">
<span class="tooltipr">
pchisq(
<span class="tooltiprtext">The `pchisq` 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 `summary(YourGlmName)` 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 `summary(YourGlmName)`.</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>
</div>
</a>
<div id="goodnessoffit1" style="display:none;">
```{r, echo=FALSE}
myglm <- glm(am ~ disp, data = mtcars, family = binomial)
summary(myglm)
pchisq(29.732, 30, lower.tail = FALSE)
```
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.
</div>
</div>
<br/>
#### Plot the Regression
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'LogisticBaseplot')">Base R</button>
<button class="tablinks" onclick="openTab(event, 'Logisticggplot')">ggplot2</button>
</div>
<div id="LogisticBaseplot" class="tabcontent">
<p>
<a href="javascript:showhide('LogisticBaseplot2')">
<div class="hoverchunk"><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">
$b_0$ +
<span class="tooltiprtext">This is the "Intercept" estimate from your logistic regression summary output.</span>
</span><span class="tooltipr">
$b_1$
<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($b_0$ + $b_1$*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>
</div>
</a>
<div id="LogisticBaseplot2" style="display:none;">
```{r, echo=FALSE}
myglm <- glm(am ~ disp, data = mtcars, family = binomial)
plot(am ~ disp, data = mtcars, pch=16)
curve(exp(2.631-0.015*x)/(1+exp(2.631-0.015*x)), add=TRUE)
```
</div>
</p>
</div>
<div id="Logisticggplot" class="tabcontent">
<p>
<a href="javascript:showhide('Logisticggplot2')">
<div class="hoverchunk"><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>
</div>
</a>
<div id="Logisticggplot2" style="display:none;">
```{r, echo=FALSE}
ggplot(mtcars, aes(disp, am)) +
geom_point() +
geom_smooth(method = "glm", method.args = list(family = "binomial"), se = FALSE) +
theme_bw()
```
</div>
</p>
</div>
<br/>
#### Predict Probabilities
To predict the probability that $Y_i=1$ for a given $x$-value, use the code
<a href="javascript:showhide('LogisticPredict')">
<div class="hoverchunk">
<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 $Y_i = 1$ for a given $X_i$.</span>
</span><span class="tooltipr">
YourGlmName,
<span class="tooltiprtext">`YourGlmName` 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 `newdata = ` command allows you to specify the x-values for which you want to obtain predicted probabilities that $Y_i=1$.</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 $Y_i = 1$ for the given $x_i$ 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>
</div>
</a>
<div id="LogisticPredict" style="display:none;">
```{r}
myglm <- glm(am ~ disp, data = mtcars, family = binomial)
predict(myglm, newdata = data.frame(disp = 200), type = "response")
```
</div>
----
</div>
### Explanation
<div style="padding-left:125px;">
Simple Logistic Regression is used when
* the response variable is binary $(Y_i=0$ or $1)$, and
* there is a single explanatory variable $X$ that is typically quantitative but could be qualitative (if $X$ is binary or ordinal).
#### The Model
Since $Y_i$ is binary (can only be 0 or 1) the model focuses on describing the probability that $Y_i=1$ for a given scenario. The probability that $Y_i = 1$ given the observed value of $x_i$ is called $\pi_i$ and is modeled by the equation
$$
P(Y_i = 1|\, x_i) = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}} = \pi_i
$$
The assumption is that for certain values of $X$ the probability that $Y_i=1$ is higher than for other values of $X$.
#### Interpretation
This model for $\pi_i$ comes from modeling the *log of the odds* that $Y_i=1$ using a linear regression, i.e.,
$$
\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}}
$$
Beginning to solve this equation for $\pi_i$ leads to the intermediate, but important result that
$$
\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}
$$
Thus, while the coefficients $\beta_0$ and $\beta_1$ are difficult to interpret directly, $e^{\beta_0}$ and $e^{\beta_1}$ have a valuable interpretation. The value of $e^{\beta_0}$ is interpreted as the odds for $Y_i=1$ when $x_i = 0$. It may not be possible for a given model to have $x_i=0$, in which case $e^{\beta_0}$ has no interpretation. The value of $e^{\beta_1}$ denotes the proportional change in the odds that $Y_i=1$ for every one unit increase in $x_i$.
Notice that solving the last equation for $\pi_i$ results in the logistic regression model presented at the beginning of this page.
#### Hypothesis Testing
Similar to linear regression, the hypothesis that
$$
H_0: \beta_1 = 0 \\
H_a: \beta_1 \neq 0
$$
can be tested with a logistic regression. If $\beta_1 = 0$, then there is no relationship between $x_i$ and the log of the odds that $Y_i = 1$. In other words, $x_i$ is not useful in predicting the probability that $Y_i = 1$. If $\beta_1 \neq 0$, then there is information in $x_i$ that can be utilized to predict the probability that $Y_i = 1$, i.e., the logistic regression is meaningful.
#### Checking Model Assumptions {#diagnostics}
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.
<div style="padding-left:15px;">
##### Deviance Goodness of Fit Test
If there are replicated values of each $x_i$, then the deviance goodness of fit test tests the hypotheses
$$
H_0: \pi_i = \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}}
$$
$$
H_a: \pi_i \neq \frac{e^{\beta_0 + \beta_1 x_i}}{1+e^{\beta_0 + \beta_1 x_i}}
$$
##### Hosmer-Lemeshow Goodness of Fit Test
If there are very few or no replicated values of each $x_i$, 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.
</div>
#### Prediction
One of the great uses of Logistic Regression is that it provides an estimate of the probability that $Y_i=1$ for a given value of $x_i$. This probability is often referred to as the *risk* that $Y_i=1$ for a certain individual. For example, if $Y_i=1$ implies a person has a disease, then $\pi_i=P(Y_i=1)$ represents the risk of individual $i$ having the disease based on their value of $x_i$, perhaps a measure of their cholesterol or some other predictor of the disease.
</div>
----
###
----
## Multiple Logistic Regression Model {.tabset .tabset-pills .tabset-fade}
<div style="float:left;width:125px;" align=center>
<img src="./Images/BinomYMultX.png" width=98px;>
</div>
Logistic regression for multiple explanatory variables that can either be quantitative or qualitative or a mixture of the two.
### Overview
<div style="padding-left:125px;">
The probability that $Y_i = 1$ given the observed data $(x_{i1},\ldots,x_{ip})$ is called $\pi_i$ and is modeled by the equation
$$
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
$$
The coefficents $\beta_0,\beta_1,\ldots,\beta_p$ are difficult to interpret directly. Typically $e^{\beta_k}$ for $k=0,1,\ldots,p$ is interpreted instead. The value of $e^{\beta_k}$ denotes the relative change in the odds that $Y_i=1$. The odds that $Y_i=1$ are $\frac{\pi_i}{1-\pi_i}$.
----
**Examples:** [GSS](./Analyses/Logistic Regression/Examples/GSSMultipleLogisticReg.html)
----
</div>
### R Instructions
<div style="padding-left:125px;">
**Console** Help Command: `?glm()`
#### Perform the Logistic Regression
To perform a logistic regression in R use the commands
<a href="javascript:showhide('logistic2')">
<div class="hoverchunk">
<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 `glm()` command.</span>
</span><span class="tooltipr">
<-
<span class="tooltiprtext">This is the "left arrow" assignment operator that stores the results of your `glm()` code into `YourGlmName`.</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 `lm(` function works except that it requires a `family=` 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,
<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 `glm(` function to perform a logistic regression. It turns out that `glm` 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 `summary` command allows you to print the results of your logistic regression that were previously saved in `YourGlmName`.</span>
</span>
</div>
</a>
<div id="logistic2" style="display:none;">
Example output from a regression. Hover each piece to learn more.
<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>
<br/>
<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 $\pi_i$ has differed from the actual outcome of $Y_i$ 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>
<br/>
<table class="rconsole">
<tr>
<td colspan="2">
<span class="tooltiprout">
Coefficients:
<span class="tooltiprouttext">Notice that in your glm(...) you used only $Y$ and $X$. You did type out any coefficients, i.e., the $\beta_0$ or $\beta_1$ 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 $\beta_j=0$</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, $\beta_0$. It is called $b_0$. 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 $b_0$. It tells you how much $b_0$ 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 $b_0$.</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 $\beta_0 = 0$. It measures the probability of observing a Z-value as extreme as the one observed. To compute it yourself in R, use `pnorm(-abs(your z-value))*2`.</span>