This repository has been archived by the owner on Oct 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
05-A-Bayesian-linear-models.html
1027 lines (942 loc) · 55.9 KB
/
05-A-Bayesian-linear-models.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 xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Jes, Jamie" />
<title>Bayesian Inference from Linear Models</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/bootstrap.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/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<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="style.css" type="text/css" />
</head>
<body>
<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%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</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;
}
</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>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<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"></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="00-computer-setup.html">Computer Setup</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W1
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="01-A-R-intro.html">Intro to R</a>
</li>
<li>
<a href="01-B-Rmarkdown-intro.html">R markdown</a>
</li>
<li>
<a href="01-C-R-workshop.html">R workshop</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W2
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="02-A-tidyr.html">ggplot2 and tidyr</a>
</li>
<li>
<a href="02-B-git-intro.html">Intro to git</a>
</li>
<li>
<a href="02-C-student-projects.html">Project introductions</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W3
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="03-A-data-exploration.html">Data exploration</a>
</li>
<li>
<a href="03-B-linear-models.html">Linear models</a>
</li>
<li>
<a href="03-C-heterogeneity.html">Heterogeneity</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W4
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="04-A-mixed-models.html">Mixed effects models</a>
</li>
<li>
<a href="04-B-binary-data.html">Binary & proportional data</a>
</li>
<li>
<a href="04-C-zero-data.html">Zero-inflated data</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W5
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="05-A-Bayesian-linear-models.html">Bayesian linear models</a>
</li>
<li>
<a href="05-B-Bayesian-priors.html">Bayesian inference with prior information</a>
</li>
<li>
<a href="05-C-Advanced-bayesian-example.html">Advanced Bayesian model example</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W6
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="06-A-unconstrained-ordination.html">Unconstrained ordination</a>
</li>
<li>
<a href="06-B-constrained-ordination.html">Constrained ordination</a>
</li>
<li>
<a href="06-C-matrix-comparison.html">Comparing multivariate data</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W8
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="08-A-mapping.html">Visualizing spatial data</a>
</li>
<li>
<a href="08-B-spatial-regression.html">Spatial regression</a>
</li>
<li>
<a href="08-C-spatial-ordination.html">Ordination approach to spatial analysis</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
W9
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="09-A-time-series.html">Time series</a>
</li>
<li>
<a href="09-B-networks.html">Network analysis</a>
</li>
<li>
<a href="09-C-occupancy-models.html">Occupancy models</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">Bayesian Inference from Linear Models</h1>
<h4 class="author"><em>Jes, Jamie</em></h4>
</div>
<p><strong>Assigned Reading:</strong></p>
<blockquote>
<p>Chapters 3, 4.1, 8.4, 9.2, in Korner-Nievergelt et al. 2015. <em>Bayesian data analysis in ecology using linear models with R, BUGS, and Stan.</em> Elsevier. <a href="http://www.sciencedirect.com/science/book/9780128013700">link</a></p>
<p>* These chapters use the same functions you have already seen. Read the assigned sections focusing on how we make Bayesian inferences from models fit with these functions.</p>
</blockquote>
<p><strong>Optional Reading:</strong></p>
<blockquote>
<p>Chapters 5, 4.2, 8, 9, in Korner-Nievergelt et al. 2015. <em>Bayesian data analysis in ecology using linear models with R, BUGS, and Stan.</em> Elsevier. <a href="http://www.sciencedirect.com/science/book/9780128013700">link</a></p>
<p>* Chapter 4.2 focuses on ANOVA-type models while the rest of chapters 8 and 9 focus on Binomial and Binary models.</p>
</blockquote>
<div id="key-points" class="section level3">
<h3>Key Points</h3>
<p>Differences between Frequentist and Bayesian approach to statistical inference:</p>
<p><strong>See Table 3.1 in the reading.</strong></p>
<table style="width:54%;">
<colgroup>
<col width="26%" />
<col width="27%" />
</colgroup>
<thead>
<tr class="header">
<th>Bayesian</th>
<th>Frequentist</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Make probabalistic statements about our state of knowledge.</td>
<td>Ask how parameter estimates change if data collected many times.</td>
</tr>
<tr class="even">
<td>Calculate probability of hypothesis, given observed data.</td>
<td>Calculate probability of data, given null hypothesis.</td>
</tr>
<tr class="odd">
<td>Likelihood is a function that calculates probability for any set of data and parameters.</td>
<td>Likelihood is a value- the probability of the observed set of data, given a specific model and estimated parameters.</td>
</tr>
<tr class="even">
<td>Inference based on samples of parameters from the posterior distribution.</td>
<td>Inference based on null hypothesis tests on values of estimated parameters and their SE.</td>
</tr>
</tbody>
</table>
<p><strong>Bayesian approach to statistical inference:</strong></p>
<p>If <span class="math inline">\(\theta\)</span> is a model and <span class="math inline">\(y\)</span> is observed data, then frequentists estimate <span class="math inline">\(P(y|\theta)\)</span> and Bayesians estimate <span class="math inline">\(P(\theta|y)\)</span>. Bayesians use:</p>
<p><span class="math display">\[p(\theta|y) = \frac{p(y|\theta) p(\theta)}{p(y)}\]</span></p>
<p><span class="math inline">\(p(\theta|y)\)</span> is the posterior distibution, <span class="math inline">\(p(\theta)\)</span> is our prior information about what values the parameters can take, and <span class="math inline">\(p(y|\theta)\)</span> is the likelihood function that gives the probability of an observed data point given a set of parameter values and a model.</p>
<ul>
<li><p>Development of algorithms that sample from posterior <span class="math inline">\(p(\theta|y)\)</span> without knowing the prior probability of the data <span class="math inline">\(p(y) = \int p(y|\theta)p(\theta) d\theta\)</span> have made Bayesian inference accessible.</p></li>
<li>Types of posterior distributions:
<ul>
<li>Joint distribution: gives probability of a set of parameter values. (Plot parameter samples to see whether parameters are correlated!)</li>
<li>Marginal distribution: gives probabilty for a particular parameter summed over all values of other parameters. (This is what you get if you summarize parameter samples independently.)</li>
<li>Conditional distribution: gives probabilty for a particular parameter holding other parameters at specific values.</li>
</ul></li>
</ul>
<p>Joint posterior distribution of <span class="math inline">\(\beta_0\)</span> and <span class="math inline">\(\beta_1\)</span>: <img src="images/05-A/unnamed-chunk-2-1.png" width="672" /></p>
<p>Marginal distribution of <span class="math inline">\(\beta_0\)</span>: <img src="images/05-A/unnamed-chunk-3-1.png" width="672" /></p>
<p>Conditional distribution of <span class="math inline">\(\beta_0\)</span> when <span class="math inline">\(\beta_1 = 4\)</span> (red line) or <span class="math inline">\(\beta_1 = 8\)</span> (blue line).</p>
<p><img src="images/05-A/unnamed-chunk-4-1.png" width="672" /></p>
<ul>
<li><p>Inference is based on <strong>visualizing</strong> and summarizing the posterior distributions of parameters, predicted future observations, and quantities calculated from parameters.</p></li>
<li>Make inferences (e.g. about effects of covariates) by summarizing samples of parameters from the posterior distribution:
<ul>
<li>Calculate median of samples to see central tendency of marginal distribution of a parameter.</li>
<li>Visualize uncertainty with credibility intervals (CrI). These give two values of a parameter between which a given percentage of samples occur.
<ul>
<li>Can be based on quantiles (symmetric), e.g. 90% CrI is between the 0.05 and 0.95 quantiles of the samples of a parameter (use <code>quantile()</code>)</li>
<li>Can be the interval with the highest posterior density (HPD): probability density within interval is never lower than probability density outside interval (use <code>HPDinterval(as.mcmc())</code>, both functions from <code>coda</code> package).</li>
</ul></li>
<li>Calculate <span class="math inline">\(\hat{y}\)</span> from samples of parameters to estimate uncertainty around predicted mean.</li>
</ul></li>
<li>Make inferences about uncertainty in future observations by sampling from the posterior predictive distribution.
<ul>
<li>Use calculated samples of <span class="math inline">\(\hat{y}\)</span> together with the likelihood (and potentially samples of <span class="math inline">\(\hat{\sigma}\)</span>) to predict future observations.</li>
<li>Combines uncertainty in parameter estimation with uncertainty in the probability model.</li>
</ul></li>
<li>Can easily calculate probabilities associated any hypothesis derived from model parameters:
<ul>
<li>Probability that future observations will be between two values.</li>
<li>Probability that the variance of <span class="math inline">\(y\)</span> among sites is greater than the variance of <span class="math inline">\(y\)</span> within sites.</li>
<li>Other examples?</li>
</ul></li>
<li><p>Bayesians use log pointwise predictive density to estimate model fit, which is analogous to the log-likelihood in Frequentist inference (see Chapter 5 and 11.2 in Korner-Nievergelt et al. 2015). For each observed outcome, it calculates the average probability of observing that outcome across all of the samples from the posterior, then adds together the ln of these probabilities.</p></li>
<li><p>Before drawing conclusions, make sure to assess the model assumptions and validate the model by looking at the residual deviance and plotting residuals.</p></li>
</ul>
<p><strong>Model notation</strong></p>
<p>To use Bayesian methods you should learn how to write down your model using matrix notation. Practice doing this with every model you fit and identifying what the columns and rows are in each matrix. Doing so will make it easier to write your own models in BUGS or Stan, which will be necessary for fitting more complex models.</p>
<p><span class="math display">\[\mathbf{y} \sim Pois(\boldsymbol{\hat{\lambda}})\\
log(\boldsymbol{\hat{\lambda}}) = \mathbf{X}\boldsymbol{\hat{\beta}}\]</span></p>
<p><span class="math inline">\(\mathbf{y}\)</span> is a vector of observations (of counts) with length <span class="math inline">\(n\)</span>.</p>
<p><span class="math inline">\(\boldsymbol{\hat{\lambda}}\)</span> is a vector of the estimated mean for each observation (has length <span class="math inline">\(n\)</span>).</p>
<p><span class="math inline">\(\mathbf{X}\)</span> is a matrix with <span class="math inline">\(n\)</span> rows and <span class="math inline">\(p\)</span> columns with the observed values of the <span class="math inline">\(p - 1\)</span> covariates in each of the rows. (Note that we have an initial column of all <span class="math inline">\(1\)</span> to estimate the mean.)</p>
<p><span class="math inline">\(\boldsymbol{\hat{\beta}}\)</span> is a vector of the parameters to be estimated with length <span class="math inline">\(p\)</span>.</p>
<p><strong>Bayesian inference in R</strong></p>
<ul>
<li>Use the <code>sim()</code> function from <code>arm</code> package to simulate samples from the posterior for models fit with <code>lm()</code>, <code>glm()</code>, <code>glmer()</code>.</li>
<li><code>sim()</code> assumes uniform (flat) prior distributions on all parameters, calculates the posterior distribution analytically, then generates random samples from this distribution.</li>
<li>Table 8.1 gives good summary of possible GLM likelihood functions and their common link functions.</li>
<li><code>model.matrix()</code> makes it easy to create design matrices for calculating fitted values (<span class="math inline">\(\hat{y}\)</span>) from samples of parameters.</li>
<li>Use the <code>apply()</code> function to summarize the matrix of parameter samples returned by <code>sim(model, n.sim)@coef</code>. <code>apply(matrix, 1, fun)</code> applies a function <code>fun</code> to the rows of the matrix whereas <code>apply(matrix, 2, fun)</code> applies the function to the columns.</li>
<li>Use <code>%*%</code> to do matrix multiplication to calculate <span class="math inline">\(\hat{y}\)</span> from samples of parameters and values of covariates.</li>
</ul>
</div>
<div id="analysis-example" class="section level3">
<h3>Analysis Example</h3>
<p>Let’s use the data from Appendix A of the Zuur book, where we are looking at the density of birds within 56 forest patches. ABUND= the density of birds in a forest patch (continuous response variable), ALT= mean altitude of the patch (continuous explanatory variable). We want to know how mean altitude of the forest patch influences the number of birds within the patch. This code comes from Chapter 3 and Chapter 4.1 in Korner-Nievergelt et al. 2015. *Bayesian data analysis in ecology using linear models with R, BUGS, and Stan.</p>
<div id="step-1-fit-a-linear-model" class="section level4">
<h4>Step 1: Fit a linear model</h4>
<p>Remember you could use any linear model from lm() glm() or glmer() but we are going to use a lm() example.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># clear your environment</span>
<span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>())
<span class="co"># read in the data</span>
<span class="co">#Loyn<- read.table(file = "/Users/jamiemcdevitt-irwin/Dropbox/Jamie/Stanford/3_Courses/Biol202/Week3_linearmodels_intro/ZuurDataMixedModelling/Loyn.txt", header = TRUE, dec = ".") </span>
Loyn <-<span class="st"> </span><span class="kw">read.table</span>(<span class="st">"data/Loyn.txt"</span>, <span class="dt">header =</span> <span class="ot">TRUE</span>)
<span class="co"># let's take a quick look at the data</span>
<span class="kw">head</span>(Loyn)</code></pre></div>
<pre><code>## Site ABUND AREA DIST LDIST YR.ISOL GRAZE ALT
## 1 1 5.3 0.1 39 39 1968 2 160
## 2 2 2.0 0.5 234 234 1920 5 60
## 3 3 1.5 0.5 104 311 1900 5 140
## 4 4 17.1 1.0 66 66 1966 3 160
## 5 5 13.8 1.0 246 246 1918 5 140
## 6 6 14.1 1.0 234 285 1965 3 130</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># run a linear regression with just one of the explanatory variables: ALT</span>
M1 <-<span class="st"> </span><span class="kw">lm</span>(ABUND ~<span class="st"> </span>ALT, <span class="dt">data =</span> Loyn) <span class="co"># least squares fit </span>
<span class="kw">summary</span>(M1)</code></pre></div>
<pre><code>##
## Call:
## lm(formula = ABUND ~ ALT, data = Loyn)
##
## Residuals:
## Min 1Q Median 3Q Max
## -19.0226 -7.5620 0.0062 8.5728 20.6834
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.59834 4.72092 1.186 0.24087
## ALT 0.09515 0.03096 3.073 0.00332 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 9.995 on 54 degrees of freedom
## Multiple R-squared: 0.1489, Adjusted R-squared: 0.1331
## F-statistic: 9.445 on 1 and 54 DF, p-value: 0.003316</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">summary</span>(M1)$sigma <span class="co"># pull out the residual standard error </span></code></pre></div>
<pre><code>## [1] 9.994817</code></pre>
<p>To get an idea of how sim() draws upon our model, let’s first write out this model fully.<br />
<strong>Random</strong><br />
<span class="math inline">\(ABUND_i \sim N(\hat{ABUND_i}, \hat{sigma})\)</span><br />
<strong>Deterministic</strong><br />
<span class="math inline">\(\hat{ABUND_i} = \hat{beta_0} + \hat{beta_1} * ALT_i\)</span></p>
</div>
<div id="step-2-draw-conclusions" class="section level4">
<h4>Step 2: Draw Conclusions</h4>
<p>Now lets use sim() in the package ‘arm’ on the model we produced ‘M1’. Sim() draws a random value from the marginal posterior distribution of sigma and then draws random values from the conditional posterior distribution of <span class="math inline">\(\beta\)</span> (i.e. the parameters in the model, in our case the intercept and slope for ALT). These posterior distributions describe the range of plausible parameter values given the data and the model. They express our uncertainty about the model parameters.</p>
<div id="simulate-values-for-theta-and-sigma" class="section level5">
<h5>Simulate values for theta and sigma</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#install.packages('arm')</span>
<span class="kw">library</span>(arm)</code></pre></div>
<pre><code>## Loading required package: Matrix</code></pre>
<pre><code>##
## Attaching package: 'Matrix'</code></pre>
<pre><code>## The following object is masked from 'package:tidyr':
##
## expand</code></pre>
<pre><code>## Loading required package: lme4</code></pre>
<pre><code>##
## Attaching package: 'lme4'</code></pre>
<pre><code>## The following object is masked from 'package:nlme':
##
## lmList</code></pre>
<pre><code>##
## arm (Version 1.9-3, built: 2016-11-21)</code></pre>
<pre><code>## Working directory is C:/Users/jrcoyle/Documents/Stanford/BIO202/GitHub</code></pre>
<pre><code>##
## Attaching package: 'arm'</code></pre>
<pre><code>## The following object is masked from 'package:car':
##
## logit</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">nsim <-<span class="dv">1000</span> <span class="co"># number of simulations can be changed to whatever you want</span>
bsim <-<span class="st"> </span><span class="kw">sim</span>(M1, <span class="dt">n.sim=</span>nsim)
<span class="kw">str</span>(bsim)</code></pre></div>
<pre><code>## Formal class 'sim' [package "arm"] with 2 slots
## ..@ coef : num [1:1000, 1:2] 4.22 6.67 8.6 2.58 6.29 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : NULL
## .. .. ..$ : chr [1:2] "(Intercept)" "ALT"
## ..@ sigma: num [1:1000] 11.18 10.82 10.12 10.28 8.67 ...</code></pre>
<p>sim() produces an object of class sim that contains “coef” (1000 simulated values for theta, i.e. your parameters) and “sigma” containing the 1000 values for SD</p>
</div>
<div id="summary-statistics-to-describe-posterior-knowledge-about-the-parameters-theta-and-the-variance" class="section level5">
<h5>Summary statistics to describe posterior knowledge about the parameters (theta) and the variance</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">apply</span>(<span class="kw">coef</span>(bsim), <span class="dv">2</span>, quantile, <span class="dt">prob=</span><span class="kw">c</span>(<span class="fl">0.025</span>, <span class="fl">0.975</span>)) <span class="co"># parameters</span></code></pre></div>
<pre><code>## (Intercept) ALT
## 2.5% -4.289248 0.02918328
## 97.5% 15.312500 0.15793703</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">quantile</span>(bsim@sigma, <span class="dt">prob=</span><span class="kw">c</span>(<span class="fl">0.025</span>, <span class="fl">0.975</span>)) <span class="co"># sigma</span></code></pre></div>
<pre><code>## 2.5% 97.5%
## 8.372159 12.366565</code></pre>
</div>
<div id="what-if-we-want-to-test-hypotheses-about-our-data-using-the-posterior-distribution" class="section level5">
<h5>What if we want to test hypotheses about our data using the posterior distribution?</h5>
<p><strong>H1.</strong></p>
<p><strong>H2.</strong> How sure are we that the slope parameter for ALT is larger than .05, .1, .2?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">set.seed</span>(<span class="dv">100</span>) <span class="co"># before you run the sim function</span>
<span class="kw">sum</span>(<span class="kw">coef</span>(bsim)[,<span class="dv">2</span>]>.<span class="dv">05</span>)/nsim <span class="co"># 93% confident that the slope is greater than .05</span></code></pre></div>
<pre><code>## [1] 0.92</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(<span class="kw">coef</span>(bsim)[,<span class="dv">2</span>]>.<span class="dv">1</span>)/nsim <span class="co"># 44% confident that the slope is greater than .1</span></code></pre></div>
<pre><code>## [1] 0.449</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(<span class="kw">coef</span>(bsim)[,<span class="dv">2</span>]>.<span class="dv">2</span>)/nsim <span class="co"># 0.1% confident that the slope is greater than .2</span></code></pre></div>
<pre><code>## [1] 0</code></pre>
</div>
<div id="what-if-we-want-to-look-at-the-effect-of-x-alt-on-y-abund-graphically-and-include-information-about-the-uncertainty-of-the-parameter-estimates" class="section level5">
<h5>What if we want to look at the effect of x (ALT) on y (ABUND) graphically and include information about the uncertainty of the parameter estimates?</h5>
<p>We use simulated values from the posterior distribution of model parameters. The simulation of the posterior distribution gives 1000 pairs of intercepts and slopes that describe 1000 different regression lines. We then draw these lines to show the uncertainty in our regression line estimation</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">plot</span>(Loyn$ALT, Loyn$ABUND, <span class="dt">pch=</span><span class="dv">16</span>, <span class="dt">las=</span><span class="dv">1</span>, <span class="dt">cex.lab=</span><span class="fl">1.2</span>)
for(i in <span class="dv">1</span>:nsim) <span class="kw">abline</span>(<span class="kw">coef</span>(bsim)[i,<span class="dv">1</span>], <span class="kw">coef</span>(bsim)[i,<span class="dv">2</span>], <span class="dt">col=</span><span class="kw">rgb</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="fl">0.05</span>)) <span class="co"># add semitransparent regression lines</span></code></pre></div>
<p><img src="images/05-A/unnamed-chunk-9-1.png" width="672" /></p>
<p>So the above plot shows you the 1000 possible regression lines that were simulated from the sim() function. The points on the plot are the original values of ABUND vs ALT</p>
</div>
<div id="plot-the-95-cris" class="section level5">
<h5>Plot the 95% CrI’s</h5>
<p>95% CrI’s: credible interval within which we expect the true parameter value to be with a probability of 0.95</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># first we must define new x-values for which we could like to make fitted values</span>
<span class="co"># find the max and min of ALT</span>
<span class="kw">min</span>(Loyn$ALT) <span class="co"># 60</span></code></pre></div>
<pre><code>## [1] 60</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">max</span>(Loyn$ALT) <span class="co"># 260</span></code></pre></div>
<pre><code>## [1] 260</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># now save these x-values because we want to then predict values past these </span>
newdat <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">ALT=</span><span class="kw">seq</span>(<span class="dv">60</span>, <span class="dv">260</span>, <span class="dt">by=</span><span class="fl">0.1</span>))
<span class="kw">head</span>(newdat)</code></pre></div>
<pre><code>## ALT
## 1 60.0
## 2 60.1
## 3 60.2
## 4 60.3
## 5 60.4
## 6 60.5</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">newmodmat <-<span class="st"> </span><span class="kw">model.matrix</span>(~ALT, <span class="dt">data=</span>newdat) <span class="co"># create a matrix that contains these new x-values</span>
<span class="kw">head</span>(newmodmat)</code></pre></div>
<pre><code>## (Intercept) ALT
## 1 1 60.0
## 2 1 60.1
## 3 1 60.2
## 4 1 60.3
## 5 1 60.4
## 6 1 60.5</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">dim</span>(newmodmat)</code></pre></div>
<pre><code>## [1] 2001 2</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fitmat <-<span class="st"> </span><span class="kw">matrix</span>(<span class="dt">ncol=</span>nsim, <span class="dt">nrow=</span><span class="kw">nrow</span>(newdat)) <span class="co"># then calculate the 1000 fitted values for each new x value using matrix multiplication</span>
<span class="kw">head</span>(fitmat)</code></pre></div>
<pre><code>## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
## [1,] NA NA NA NA NA NA NA NA NA NA NA NA NA
## [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,36] [,37] [,38] [,39] [,40] [,41] [,42] [,43] [,44] [,45] [,46]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,47] [,48] [,49] [,50] [,51] [,52] [,53] [,54] [,55] [,56] [,57]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,58] [,59] [,60] [,61] [,62] [,63] [,64] [,65] [,66] [,67] [,68]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,69] [,70] [,71] [,72] [,73] [,74] [,75] [,76] [,77] [,78] [,79]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,80] [,81] [,82] [,83] [,84] [,85] [,86] [,87] [,88] [,89] [,90]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,91] [,92] [,93] [,94] [,95] [,96] [,97] [,98] [,99] [,100] [,101]
## [1,] NA NA NA NA NA NA NA NA NA NA NA
## [,102] [,103] [,104] [,105] [,106] [,107] [,108] [,109] [,110] [,111]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,112] [,113] [,114] [,115] [,116] [,117] [,118] [,119] [,120] [,121]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,122] [,123] [,124] [,125] [,126] [,127] [,128] [,129] [,130] [,131]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,132] [,133] [,134] [,135] [,136] [,137] [,138] [,139] [,140] [,141]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,142] [,143] [,144] [,145] [,146] [,147] [,148] [,149] [,150] [,151]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,152] [,153] [,154] [,155] [,156] [,157] [,158] [,159] [,160] [,161]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,162] [,163] [,164] [,165] [,166] [,167] [,168] [,169] [,170] [,171]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,172] [,173] [,174] [,175] [,176] [,177] [,178] [,179] [,180] [,181]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,182] [,183] [,184] [,185] [,186] [,187] [,188] [,189] [,190] [,191]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,192] [,193] [,194] [,195] [,196] [,197] [,198] [,199] [,200] [,201]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,202] [,203] [,204] [,205] [,206] [,207] [,208] [,209] [,210] [,211]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,212] [,213] [,214] [,215] [,216] [,217] [,218] [,219] [,220] [,221]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,222] [,223] [,224] [,225] [,226] [,227] [,228] [,229] [,230] [,231]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,232] [,233] [,234] [,235] [,236] [,237] [,238] [,239] [,240] [,241]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,242] [,243] [,244] [,245] [,246] [,247] [,248] [,249] [,250] [,251]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,252] [,253] [,254] [,255] [,256] [,257] [,258] [,259] [,260] [,261]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,262] [,263] [,264] [,265] [,266] [,267] [,268] [,269] [,270] [,271]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,272] [,273] [,274] [,275] [,276] [,277] [,278] [,279] [,280] [,281]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,282] [,283] [,284] [,285] [,286] [,287] [,288] [,289] [,290] [,291]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,292] [,293] [,294] [,295] [,296] [,297] [,298] [,299] [,300] [,301]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,302] [,303] [,304] [,305] [,306] [,307] [,308] [,309] [,310] [,311]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,312] [,313] [,314] [,315] [,316] [,317] [,318] [,319] [,320] [,321]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,322] [,323] [,324] [,325] [,326] [,327] [,328] [,329] [,330] [,331]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,332] [,333] [,334] [,335] [,336] [,337] [,338] [,339] [,340] [,341]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,342] [,343] [,344] [,345] [,346] [,347] [,348] [,349] [,350] [,351]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,352] [,353] [,354] [,355] [,356] [,357] [,358] [,359] [,360] [,361]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,362] [,363] [,364] [,365] [,366] [,367] [,368] [,369] [,370] [,371]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,372] [,373] [,374] [,375] [,376] [,377] [,378] [,379] [,380] [,381]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,382] [,383] [,384] [,385] [,386] [,387] [,388] [,389] [,390] [,391]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,392] [,393] [,394] [,395] [,396] [,397] [,398] [,399] [,400] [,401]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,402] [,403] [,404] [,405] [,406] [,407] [,408] [,409] [,410] [,411]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,412] [,413] [,414] [,415] [,416] [,417] [,418] [,419] [,420] [,421]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,422] [,423] [,424] [,425] [,426] [,427] [,428] [,429] [,430] [,431]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,432] [,433] [,434] [,435] [,436] [,437] [,438] [,439] [,440] [,441]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,442] [,443] [,444] [,445] [,446] [,447] [,448] [,449] [,450] [,451]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,452] [,453] [,454] [,455] [,456] [,457] [,458] [,459] [,460] [,461]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,462] [,463] [,464] [,465] [,466] [,467] [,468] [,469] [,470] [,471]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,472] [,473] [,474] [,475] [,476] [,477] [,478] [,479] [,480] [,481]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,482] [,483] [,484] [,485] [,486] [,487] [,488] [,489] [,490] [,491]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,492] [,493] [,494] [,495] [,496] [,497] [,498] [,499] [,500] [,501]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,502] [,503] [,504] [,505] [,506] [,507] [,508] [,509] [,510] [,511]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,512] [,513] [,514] [,515] [,516] [,517] [,518] [,519] [,520] [,521]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,522] [,523] [,524] [,525] [,526] [,527] [,528] [,529] [,530] [,531]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,532] [,533] [,534] [,535] [,536] [,537] [,538] [,539] [,540] [,541]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,542] [,543] [,544] [,545] [,546] [,547] [,548] [,549] [,550] [,551]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,552] [,553] [,554] [,555] [,556] [,557] [,558] [,559] [,560] [,561]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,562] [,563] [,564] [,565] [,566] [,567] [,568] [,569] [,570] [,571]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,572] [,573] [,574] [,575] [,576] [,577] [,578] [,579] [,580] [,581]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,582] [,583] [,584] [,585] [,586] [,587] [,588] [,589] [,590] [,591]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,592] [,593] [,594] [,595] [,596] [,597] [,598] [,599] [,600] [,601]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,602] [,603] [,604] [,605] [,606] [,607] [,608] [,609] [,610] [,611]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,612] [,613] [,614] [,615] [,616] [,617] [,618] [,619] [,620] [,621]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,622] [,623] [,624] [,625] [,626] [,627] [,628] [,629] [,630] [,631]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,632] [,633] [,634] [,635] [,636] [,637] [,638] [,639] [,640] [,641]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,642] [,643] [,644] [,645] [,646] [,647] [,648] [,649] [,650] [,651]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,652] [,653] [,654] [,655] [,656] [,657] [,658] [,659] [,660] [,661]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,662] [,663] [,664] [,665] [,666] [,667] [,668] [,669] [,670] [,671]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,672] [,673] [,674] [,675] [,676] [,677] [,678] [,679] [,680] [,681]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,682] [,683] [,684] [,685] [,686] [,687] [,688] [,689] [,690] [,691]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,692] [,693] [,694] [,695] [,696] [,697] [,698] [,699] [,700] [,701]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,702] [,703] [,704] [,705] [,706] [,707] [,708] [,709] [,710] [,711]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,712] [,713] [,714] [,715] [,716] [,717] [,718] [,719] [,720] [,721]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,722] [,723] [,724] [,725] [,726] [,727] [,728] [,729] [,730] [,731]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,732] [,733] [,734] [,735] [,736] [,737] [,738] [,739] [,740] [,741]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,742] [,743] [,744] [,745] [,746] [,747] [,748] [,749] [,750] [,751]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,752] [,753] [,754] [,755] [,756] [,757] [,758] [,759] [,760] [,761]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,762] [,763] [,764] [,765] [,766] [,767] [,768] [,769] [,770] [,771]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,772] [,773] [,774] [,775] [,776] [,777] [,778] [,779] [,780] [,781]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,782] [,783] [,784] [,785] [,786] [,787] [,788] [,789] [,790] [,791]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,792] [,793] [,794] [,795] [,796] [,797] [,798] [,799] [,800] [,801]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,802] [,803] [,804] [,805] [,806] [,807] [,808] [,809] [,810] [,811]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,812] [,813] [,814] [,815] [,816] [,817] [,818] [,819] [,820] [,821]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,822] [,823] [,824] [,825] [,826] [,827] [,828] [,829] [,830] [,831]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,832] [,833] [,834] [,835] [,836] [,837] [,838] [,839] [,840] [,841]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,842] [,843] [,844] [,845] [,846] [,847] [,848] [,849] [,850] [,851]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,852] [,853] [,854] [,855] [,856] [,857] [,858] [,859] [,860] [,861]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,862] [,863] [,864] [,865] [,866] [,867] [,868] [,869] [,870] [,871]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,872] [,873] [,874] [,875] [,876] [,877] [,878] [,879] [,880] [,881]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,882] [,883] [,884] [,885] [,886] [,887] [,888] [,889] [,890] [,891]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,892] [,893] [,894] [,895] [,896] [,897] [,898] [,899] [,900] [,901]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,902] [,903] [,904] [,905] [,906] [,907] [,908] [,909] [,910] [,911]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,912] [,913] [,914] [,915] [,916] [,917] [,918] [,919] [,920] [,921]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,922] [,923] [,924] [,925] [,926] [,927] [,928] [,929] [,930] [,931]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,932] [,933] [,934] [,935] [,936] [,937] [,938] [,939] [,940] [,941]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,942] [,943] [,944] [,945] [,946] [,947] [,948] [,949] [,950] [,951]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,952] [,953] [,954] [,955] [,956] [,957] [,958] [,959] [,960] [,961]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,962] [,963] [,964] [,965] [,966] [,967] [,968] [,969] [,970] [,971]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,972] [,973] [,974] [,975] [,976] [,977] [,978] [,979] [,980] [,981]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,982] [,983] [,984] [,985] [,986] [,987] [,988] [,989] [,990] [,991]
## [1,] NA NA NA NA NA NA NA NA NA NA
## [,992] [,993] [,994] [,995] [,996] [,997] [,998] [,999] [,1000]
## [1,] NA NA NA NA NA NA NA NA NA
## [ reached getOption("max.print") -- omitted 5 rows ]</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">dim</span>(fitmat)</code></pre></div>
<pre><code>## [1] 2001 1000</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">for(i in <span class="dv">1</span>:nsim) fitmat[,i] <-<span class="st"> </span>newmodmat %*%<span class="st"> </span><span class="kw">coef</span>(bsim)[i,] <span class="co"># %*% is for matrix multiplication, recall that bsim is the object sim() produced for our model M1</span>
<span class="co"># so you are multiplying the new x values created from the min and max of x by the bsim values </span>
<span class="kw">plot</span>(Loyn$ALT,Loyn$ABUND, <span class="dt">pch=</span><span class="dv">16</span>, <span class="dt">las=</span><span class="dv">1</span>, <span class="dt">cex.lab=</span><span class="fl">1.2</span>)
<span class="kw">abline</span>(M1, <span class="dt">lw=</span><span class="dv">2</span>) <span class="co"># add line from our original model</span>
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(fitmat, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.025</span>), <span class="dt">lty=</span><span class="dv">3</span>)
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(fitmat, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.975</span>), <span class="dt">lty=</span><span class="dv">3</span>) </code></pre></div>
<p><img src="images/05-A/unnamed-chunk-10-1.png" width="672" /></p>
<p>We are 95% sure the true regression line (black line) is within the credible interval (dotted lines)</p>
</div>
<div id="what-if-we-want-to-predict-future-observations" class="section level5">
<h5>What if we want to predict future observations?</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># prepare matrix for simulated new data</span>
newy <-<span class="st"> </span><span class="kw">matrix</span>(<span class="dt">ncol=</span>nsim, <span class="dt">nrow=</span><span class="kw">nrow</span>(newdat)) <span class="co"># recall newdata is the new x values we created earlier </span>
<span class="co"># for each simulated fitted value (x=ALT), simulate one new y-value (y=ABUND)</span>
for(i in <span class="dv">1</span>:nsim) newy[,i] <-<span class="st"> </span><span class="kw">rnorm</span>(<span class="kw">nrow</span>(newdat),<span class="dt">mean=</span>fitmat[,i],<span class="dt">sd=</span>bsim@sigma[i])
<span class="co"># call the plot with the 95% credible interval prior to adding the 95% interval of simulated predictive distribution</span>
<span class="kw">plot</span>(Loyn$ALT,Loyn$ABUND, <span class="dt">pch=</span><span class="dv">16</span>, <span class="dt">las=</span><span class="dv">1</span>, <span class="dt">cex.lab=</span><span class="fl">1.2</span>)
<span class="kw">abline</span>(M1, <span class="dt">lw=</span><span class="dv">2</span>) <span class="co"># add line from our original model</span>
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(fitmat, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.025</span>), <span class="dt">lty=</span><span class="dv">3</span>)
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(fitmat, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.975</span>), <span class="dt">lty=</span><span class="dv">3</span>)
<span class="co"># 95% interval of simulated predictive distribution</span>
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(newy, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.025</span>), <span class="dt">lty=</span><span class="dv">2</span>)
<span class="kw">lines</span>(newdat$ALT, <span class="kw">apply</span>(newy, <span class="dv">1</span>, quantile, <span class="dt">prob=</span><span class="fl">0.975</span>), <span class="dt">lty=</span><span class="dv">2</span>)</code></pre></div>
<p><img src="images/05-A/unnamed-chunk-11-1.png" width="672" /></p>
<p>Thus, future observations are expected to be within the interval defined by the broken lines in the figure above with a probability of 0.95.</p>
<p>Note: compared to a frequentist approach (predict()), this takes a lot more code. However, when you have a simulated the posterior predictive distribution, you have more information than is contained in the frequentist prediction interval. For example, you can test hypotheses about future observations (see code below)</p>
</div>
<div id="from-these-predicted-future-values-we-can-give-an-estimate-for-the-proportion-of-observations-i.e.density-of-birds-greater-than-given-the-mean-altitude" class="section level5">
<h5>From these predicted future values, we can give an estimate for the proportion of observations (i.e. density of birds) greater than #, given the mean altitude =</h5>
<p><strong>EX1.</strong> If ALT=60, what is the estimated proportion of observations greater than 20?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(newy[newdat$ALT==<span class="dv">60</span>,]><span class="dv">20</span>)/nsim</code></pre></div>
<pre><code>## [1] 0.192</code></pre>
<p>Thus we expect 20% of future observations with ALT=60 to have a density of birds greater than 20</p>
<p><strong>EX2.</strong> IF ALT=120, what is the estimated proportion of observations greater than 20?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(newy[newdat$ALT==<span class="dv">120</span>,]><span class="dv">20</span>)/nsim</code></pre></div>
<pre><code>## [1] 0.401</code></pre>
<p>Thus we expect 39% of future observations with ALT=120 to have a density of birds greater than 20</p>
<p>Another reason to learn this is because once you have a more complicated model (e.g. mixed models), the frequentist methods to obtain confidence intervals of fitted values are much more complicated than the Bayesian method presented here. The code we learned here can be used for mixed models and generalized linear mixed models with minor changes.</p>
</div>
</div>
</div>
<div id="discussion-questions" class="section level3">
<h3>Discussion Questions</h3>
<ol style="list-style-type: decimal">
<li>Why is it harder to obtain CI for fitted values in frequentist approaches?<br />
</li>
<li>When/Why would you bother to use sim() if you don’t have priors? Would it help validate your lm()?<br />
</li>
<li>What type of prior knowledge could you think of adding to this example data (X=Altitude, Y=Density) (if it existed)?<br />
</li>
<li>Where would the priors go into the model equation (i.e. write out the model equation in matrices, where would the priors be?)?</li>
</ol>
</div>
</div>
</div>