-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgimenez_lectures.Rmd
executable file
·3599 lines (2567 loc) · 102 KB
/
gimenez_lectures.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: "Statistics for Ecologists"
author: "Olivier Gimenez"
date: "October 2020"
output:
beamer_presentation:
fig_caption: no
includes:
in_header: header.tex
latex_engine: xelatex
slide_level: 2
theme: metropolis
ioslides_presentation: default
classoption: aspectratio=169
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(cache = TRUE,
echo = TRUE,
message = FALSE,
warning = FALSE,
fig.asp = 0.62,
fig.width = 5,
fig.align = "center",
tidy = FALSE,
comment = NA,
highlight = TRUE,
prompt = FALSE,
crop = TRUE,
comment = "#>",
collapse = TRUE,
dpi = 300)
knitr::opts_knit$set(width = 60)
library(reshape2)
library(tidyverse)
theme_set(theme_light(base_size = 12))
library(R2jags)
library(broom)
library(visreg)
library(DHARMa)
make_latex_decorator <- function(output, otherwise) {
function() {
if (knitr:::is_latex_output()) output else otherwise
}
}
```
# Who's that guy?!
## Adorator of memes
```{r echo=FALSE}
knitr::include_graphics("img/love_stats_cats.jpg")
```
## Olivier Gimenez
* Senior scientist at CNRS, Montpellier - France
* Trained as a statistician
* Soon attracted by the bright side of ecology
* Interface of animal demography, statistical modeling and social sciences
* More on <https://oliviergimenez.github.io/>
* Twitter @oaggimenez
# Your turn
```{r, echo = FALSE}
knitr::include_graphics("img/that-moment-when-the-teacher-asks-you-to-introduce-yourself-to-the-class.jpg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_002.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_003.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_004.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_005.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_006.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_007.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_008.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_009.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_010.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_012.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_013.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_014.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_015.jpeg")
```
##
```{r echo = FALSE, out.width="90%"}
knitr::include_graphics("img/ecostat_largecarnivores_light_Page_016.jpeg")
```
# Acknowledgments
## Acknowledgments
* Sean Anderson, Jason Matthiopoulos, Denis Réale, Francisco Rodriguez-Sanchez and Ruth King for sharing their courses material
# This Class
## Slides, R codes, data and practicals
* I used `R`, and `RStudio`
* I also used `R Markdown` to write reproducible documents (slides/exercises)
* All material is available on GitHub <https://github.com/oliviergimenez/statistics-for-ecologists-Master-courses>
* Check out the files `gimenez_lectures.R` and `gimenez_practicals.R`
* You will need the following `R` packages: `arm`, `bbmle`, `broom`, `tidyverse`, `effects`, `visreg`, `lme4`, `MuMIn`, `R2jags`
## On our plate
* Distributions and likelihoods
* Hypothesis testing and multimodel inference
* Introduction to Bayesian inference
* Generalized Linear Models (GLMs)
* Generalized Additive Models (GAMs)
* Mixed Effect Models
## On our plate
* \alert{Distributions and likelihoods}
* Hypothesis testing and multimodel inference
* Introduction to Bayesian inference
* Generalized Linear Models (GLMs)
* Generalized Additive Models (GAMs)
* Mixed Effect Models
# Distributions and likelihoods
## Distributions
* What for?
* Conceptual models, bearing in mind that:
> All models are wrong, but some are useful (G.E.P. Cox, 1976)
* Either represent how the world works
* Or capture the behavior of a statistic under some null hypothesis we'd like to test
* Discrete or continuous
# Discrete distributions
## Bernoulli distribution
**Context**: A single trial with two outcomes, success/failure
$X \sim \text{Bern}(p)$ with $p$ probability of having a success
| $x$ | $P(X=x)$ |
|----+-----------|
| 1 | $p$ |
| 0 | $1-p$ |
**Example**: $X$ is the random variable *being born a female*
## Ten Bernoulli trials with $p=0.5$
```{r, echo=FALSE}
data.frame(value = rbinom(10,1,0.5)) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
mutate(value = fct_recode(value, "male" = "0", "female" = "1")) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n)) +
geom_col(fill = "#009E73", color = "black") +
labs(x = "", y = "")
```
## Ten Bernoulli trials with $p=0.5$, again
```{r, echo=FALSE}
set.seed(1979)
rbinom(10,1,0.5) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
mutate(levels = fct_recode(value, "male" = "0", "female" = "1")) %>%
dplyr::count(levels) %>%
ggplot(aes(x = levels, y = n)) +
geom_col(fill = "#009E73", color = "black") +
labs(x = "", y = "")
```
## Hundred Bernoulli trials with $p=0.5$
```{r, echo=FALSE}
rbinom(100,1,0.5) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
mutate(levels = fct_recode(value, "male" = "0", "female" = "1")) %>%
dplyr::count(levels) %>%
ggplot(aes(x = levels, y = n)) +
geom_col(fill = "#009E73", color = "black") +
labs(x = "", y = "")
```
## Hundred Bernoulli trials with $p=0.2$
```{r, echo=FALSE}
rbinom(100,1,0.2) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
mutate(levels = fct_recode(value, "male" = "0", "female" = "1")) %>%
dplyr::count(levels) %>%
ggplot(aes(x = levels, y = n)) +
geom_col(fill = "#009E73", color = "black") +
labs(x = "", y = "")
```
## Hundred Bernoulli trials with $p=0.8$
```{r, echo=FALSE}
rbinom(100,1,0.8) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
mutate(levels = fct_recode(value, "male" = "0", "female" = "1")) %>%
dplyr::count(levels) %>%
ggplot(aes(x = levels, y = n)) +
geom_col(fill = "#009E73", color = "black") +
labs(x = "", y = "")
```
## Summary: Bernoulli distribution
* **notation**: $X \sim \text{Bern}(p)$
* **range**: discrete, $x = 0, 1$
* **distribution**: $P(X=x) = p^x (1-p)^{1-x}$
* **parameters**: $p$ is the probability of success
* **mean**: $p$
* **variance**: $p(1-p)$
## Binomial distribution
**Context**: Total number of successes from a fixed number of independent Bernoulli trials, all with same probability of success
$X \sim \text{Bin}(N,p)$ with $p$ probability of having a success and $N$ number of trials
$$P(X=x) = {{N!}\over{x!(N-x)!}}p^x(1-p)^{N-x} = \binom{N}{x}p^x(1-p)^{N-x}$$
**Example**: $X$ is the random variable *number of heads in a series of coin flipping*
## Binomial distribution
$$P(X=x) = \binom{N}{x}p^x(1-p)^{N-x}$$
| $x$ | $P(X=x)$ |
|----+-----------|
| 0 | $(1-p)^N$ |
| 1 | $Np(1-p)^{N-1}$ |
| ... | ... |
| N | $p^N$ |
## Binomial distribution
| $x$ | $P(X=x)$ |
|----+-----------|
| 0 | $(1-p)^N$ |
| 1 | $Np(1-p)^{N-1}$ |
| ... | ... |
| N | $p^N$ |
Fortunately, ```R``` has this pre-programmed
```{r,collapse=TRUE}
dbinom(x = 1, size = 10, prob = 0.5) # equals 10*0.5*(1-0.5)^(10-1)
```
## Hundred Binomial trials with $N=10$ and $p=0.5$
```{r, echo=FALSE}
rbinom(100,10,0.5) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(palette = "PiYG") +
theme(legend.position = "none")
```
## Hundred Binomial trials with $N=10$ and $p=0.5$, again
```{r, echo=FALSE}
rbinom(100,10,0.5) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(palette = "PiYG") +
theme(legend.position = "none")
```
## Hundred Binomial trials with $N=10$ and $p=0.2$
```{r, echo=FALSE}
rbinom(100,10,0.2) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(palette = "PiYG") +
theme(legend.position = "none")
```
## Hundred Binomial trials with $N=10$ and $p=0.8$
```{r, echo=FALSE}
rbinom(100,10,0.8) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(palette = "PiYG") +
theme(legend.position = "none")
```
## Playing around with probabilities
\begin{itemize}[<+- | alert@+>]
\item Let's say $X \sim \text{Bin}(N=10,p=0.5)$ is a random variable counting the number of males
\item What is the probability of having at most 1 male?
\item $P(X \leq 1) = P(X=0) + P(X=1)$
\item How to compute this in R?
\item dbinom(x=0,size=10,prob=0.5) + dbinom(x=1,size=10,prob=0.5)
\end{itemize}
## Summary: Binomial distribution
* **notation**: $X \sim \text{Bin}(N,p)$
* **range**: discrete, $0 \leq x \leq N$
* **distribution**: $P(X=x) = \binom{N}{x}p^x (1-p)^{1-x}$
* **parameters**: $p$ the probability of success, and $N$ the number of trials
* **mean**: $Np$
* **variance**: $Np(1-p)$
* **in R**: ```rbinom```, ```dbinom```
## Poisson distribution
**Context**: Number of occurrences of an event over a given unit of space or time.
$X \sim \text{Poisson}(\lambda)$ with $\lambda$ expected number of occurrences
$$P(X=x) = {{e^{-\lambda}\lambda^x}\over{x!}}$$
**Example**: $X$ is the random variable *number of birds counted on a colony during the breeding season*
## Poisson distribution
$$P(X=x) = {{e^{-\lambda}\lambda^x}\over{x!}}$$
| $x$ | $P(X=x)$ |
|----+-----------|
| 0 | $e^{-\lambda}$ |
| 1 | $\lambda e^{-\lambda}$ |
| ... | ... |
## Poisson distribution
| $x$ | $P(X=x)$ |
|----+-----------|
| 0 | $e^{-\lambda}$ |
| 1 | $\lambda e^{-\lambda}$ |
| ... | ... |
Fortunately, ```R``` has this pre-programmed
```{r,collapse=TRUE}
dpois(x=0,lambda=3) # equals exp(-3)
```
## Hundred Poisson trials with $\lambda=1$
```{r, echo=FALSE}
rpois(n = 100, lambda = 1) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(direction = -1, palette = "PuOr") +
theme(legend.position = "none")
```
## Hundred Poisson trials with $\lambda=2$
```{r, echo=FALSE}
rpois(n = 100, lambda = 2) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
scale_fill_brewer(direction = -1, palette = "PuOr") +
theme(legend.position = "none")
```
## Hundred Poisson trials with $\lambda=10$
```{r, echo=FALSE}
rpois(n = 100, lambda = 10) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
theme(legend.position = "none")
```
## Thousand Poisson trials with $\lambda=10$
```{r, echo=FALSE}
rpois(n = 1000, lambda = 10) %>%
as_tibble() %>%
mutate(value = as_factor(value)) %>%
dplyr::count(value) %>%
ggplot(aes(x = value, y = n, fill = value)) +
geom_col() +
labs(x = "", y = "") +
theme(legend.position = "none")
```
## Summary: Poisson distribution
* **notation**: $X \sim \text{Poisson}(\lambda)$
* **range**: discrete, $x \geq 0$
* **distribution**: $P(X=x) = {{e^{-\lambda}\lambda^x}\over{x!}}$
* **parameters**: $\lambda$ the rate or expected number per sample
* **mean**: $\lambda$
* **variance**: $\lambda$
* **in R**: ```rpois```, ```dpois```
# Continuous distribution
## Normal (Gaussian) distribution
**Context**: Distribution of “adding lots of things together”. Derived from *Central Limit Theorem*, which says that if you add a large number of independent samples from the same distribution the distribution of the sum
will be approximately normal.
$X \sim \text{Normal}(\mu,\sigma^2)$ where $\mu$ is the mean and $\sigma^2$ the variance
$$f(x) = {{1}\over{\sqrt{2\pi\sigma}}}\exp\left( - {{(x-\mu)^2}\over{2\sigma^2}} \right)$$
**Example**: Practically everything.
## Normal probability density function
```{r, echo=FALSE, fig.width=6}
min.x <- -5
max.x <- 5
num.samples <- 1000
x <- seq(from = min.x, to = max.x, length = num.samples)
# Open new blank plot with x limits from -5 to 5, and y limits from 0 to 1
plot(c(-5, 5), c(0, 1), xlab = 'x', ylab = 'f(x)', main = "", type = "n")
# Add each density plot one at a time
lines(x, dnorm(x, mean = 0, sd = 0.5), lwd = 3, col = 'red')
lines(x, dnorm(x, mean = 0, sd = 1), lwd = 3, col = 'green')
lines(x, dnorm(x, mean = 0, sd = 2), lwd =3, col = 'blue')
lines(x, dnorm(x, mean = -2, sd = 1), lwd = 3, col = 'magenta')
# We can also add a legend to the plot
legend("topright",
c("mu=0, sigma=0.5", "mu=0, sigma=1", "mu=0, sigma=2", "mu=-2, sigma=1"),
col = c('red','green','blue','magenta'),
lty = 1,
lwd = 3)
```
## Summary: Normal distribution
* **notation**: $X \sim \text{N}(\mu,\sigma^2)$
* **range**: continuous, all real values
* **distribution**: $f(x) = {{1}\over{\sqrt{2\pi\sigma}}}\exp\left( - {{(x-\mu)^2}\over{2\sigma^2}} \right)$
* **parameters**: $\mu$ the mean and $\sigma$ the standard deviation
* **mean**: $\mu$
* **variance**: $\sigma^2$
* **in R**: ```rnorm```, ```dnorm```
## Why do we love the Normal distribution
```{r echo = FALSE}
knitr::include_graphics("img/paranormal.jpg")
```
## Why do we love the Normal distribution
* If has nice properties, such as: if $X \sim \text{N}(\mu,\sigma^2)$, then $Z = \displaystyle{{{X - \mu}\over{\sigma}} \sim \text{N}(0,1)}$
* It is a limiting distribution (*Central Limit Theorem*)
* It can be a good approximation for other distributions
## Example: Approximating Binomial by Normal (1)
$X \sim \text{Bin}(N=50,p=0.3)$
Mean is $Np = 50 \times 0.3 = 15$
Variance is $Np(1-p) = 50 \times 0.3 \times 0.7 = 10.5$
Therefore, $X$ can be approximated by $Y \sim \text{N}(15,\sigma=\sqrt{10.5})$
## Example: Approximating Binomial by Normal (2)
```{r, echo=FALSE}
n<-50
p<-0.3
f<-hist(rbinom(100000, n,p), freq=FALSE, breaks=n/2,main="", xlab="x")
x<-f$breaks
lines(x,dnorm(x,n*p,sqrt(n*p*(1-p))),col='red',lwd=3)
abline(v=15,lwd=2,col='blue',lty=2)
```
# Conclusions about distributions
## Common Distributions - Discrete
* When we have something that is dichotomous (either 0 or 1, negative/positive, false/true, male/female, present/absent):
$$\text{Binomial(number of trials, probability)}$$
* When we have something that is a discrete count, with no theoretical maximum, but with a common average:
$$\text{Poisson(lambda)}$$
## Common Distributions - Discrete
* When we are recording the number of *failures* before a number of *successes*, or when we have something that is a discrete count with no theoretical maximum, and with more variation than Poisson:
$$\text{NegativeBinomial(number of successes, probability of success)}$$
$$\text{NegativeBinomial(mean, overdispersion)}$$
## Common Distributions - Continuous
* When we have something that is continuous, symmetrical about the mean and unbounded:
$$\text{Normal(mean, standard deviation)}$$
* When we have something that is continuous, not symmetrical, and bounded at zero:
$$\text{Exponential(rate)}$$
$$\text{Gamma(shape, rate)}$$
## Common Distributions - Continuous
* When we have something that is continuous, not symmetrical, and bounded at zero:
$$\text{Lognormal(logmean, logstdev)}$$
* When we have something that is continuous, and bounded between 0 and 1:
$$\text{Beta(alpha, beta)}$$
* Simple bounded distribution:
$$\text{Uniform(min, max)}$$
## More? Check out in R:
```{r}
?Distributions
```
# Likelihoods
## Fitting distributions to data
* So far, when talking about probability distributions, we assumed that we
knew the parameter values
* And we wanted to know what data we might get from these distributions
* In the real world, it is usually the other way around
* A more relevant question might be:
> We have observed 3 births by a female during her 10 breeding
attempts. What does this tell us about the true probability of
getting a successful breeding attempt from this female? For the population?
## Fitting distributions to data
We don’t know what the probability of a birth is, but we can see what the probability of getting our data would be for different
values:
```{r,collapse=TRUE}
dbinom(x = 3, size = 10, prob = 0.1)
```
## Fitting distributions to data
We don’t know what the probability of a birth is, but we can see what the probability of getting our data would be for different
values:
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.9)
```
## Fitting distributions to data
We don’t know what the probability of a birth is, but we can see what the probability of getting our data would be for different
values:
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.25)
```
So we would be more likely to observe 3 births if the probability is
0.25 than 0.1 or 0.9
## The likelihood
* This reasoning is so common in statistics that it has a special name:
* \alert{The likelihood} is the probability of observing the data under a certain model
* The data are known, we usually consider the likelihood as a function of the model parameters $\theta_1,\theta_2, \ldots, \theta_p$
$$L = P(\theta_1,\theta_2, \ldots, \theta_p \mid \text{data})$$
* This is a very important concept
## Likelihood functions
We may create a function to calculate a likelihood e.g.:
```{r,collapse=TRUE}
lik.fun <- function(parameter){
ll <- dbinom(x=3, size=10, prob=parameter)
return(ll)
}
lik.fun(0.3)
lik.fun(0.6)
```
## Maximize the likelihood (3 successes ot of 10 attempts)
```{r, echo=FALSE}
lik.fun <- function(parameter){
ll <- dbinom(x=3, size=10, prob=parameter)
return(ll)
}
p.grid = seq(0,1,by=0.01)
lik = rep(NA,length(p.grid))
for (i in 1:length(p.grid)){
lik[i] <- lik.fun(p.grid[i])
}
plot(p.grid, lik,
xlab = 'prob. of getting a successful breeding attempt',
ylab = 'likelihood',
type = 'l',
lwd = 3)
abline(v = 0.3,
lty = 2,
lwd = 2,
col = 'blue')
```
The *maximum* of the likelihood is at value $0.3$
## The Maximum Likelihood
* There is always a set of parameters that gives you the highest likelihood of observing the data: the \alert{Maximum Likelihood Estimate(s) [MLEs]}
* This can be calculated using:
+ Trial and error (not efficient!)
+ Compute the maximum of a function by hand (rarely doable in practice)
+ An iterative optimization algorithm: Check out `?optim` function in `R`
## \alert{By hand}: compute MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
$P(Y=k) = {{k}\choose{N}} p^k (1-p)^{N-k} = L(p)$
$\log(L(p)) = \text{cte} + k \log(p) + (N-k) \log(1-p)$
We are searching for the maximum of $L$, or equivalently that of $\log(L)$
Compute derivate w.r.t. $p$: $\displaystyle{{{d\log(L)}\over{dp}} = {{k}\over{p}} – {{(N-k)}\over{(1-p)}}}$
Then solve $\displaystyle{{{d\log(L)}\over{dp}}=0}$; the MLE is $\displaystyle{\hat{p} = {{k}\over{N}}={{3}\over{10}}=0.3}$
Here, the MLE is the proportion of observed successes
## \alert{Using a computer}: MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
```{r,collapse=TRUE}
lik.fun <- function(parameter) -dbinom(x=3, size=10, prob=parameter)
# ?optim (by default, minimize)
init <- 0.5
optim(init, lik.fun)
```
Use `optim` when the number of parameters is $> 1$.
## \alert{Using a computer}: MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
```{r, echo=FALSE}
lik.fun <- function(parameter) dbinom(x=3, size=10, prob=parameter)
plot(lik.fun,0,1,xlab="probability of success (p)",ylab="log-likelihood(p)",main="",lwd=3)
abline(v=0.3,h=0.26682,col='blue',lty=2,lwd=2)
```
## The Maximum Likelihood Estimate (MLE)
* \alert{The MLE is the best guess set of parameter values for our given data}
## A dart target, with the red cross representing the true parameter value
```{r echo = FALSE}
library(plotrix)
plot(0,0,type = "n", xlim = c(-1.4,1.4), ylim = c(-10,10),axes=F,xlab='',ylab='',main = 'Imprecise and biased')
draw.circle(0,0,radius=0.7,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.5,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.3,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.1,lty=1,lwd=2,border='black')
points(0,0,col='red',cex=2,pch=4)
for (i in 1:35){
points(runif(1,-0.3,0.5),runif(1,2,6.5),col='blue',cex=1,pch=19)
}
```
## A dart target, with the red cross representing the true parameter value
```{r echo = FALSE}
plot(0,0,type = "n", xlim = c(-1.4,1.4), ylim = c(-10,10),axes=F,xlab='',ylab='',main = 'Precise but biased')
draw.circle(0,0,radius=0.7,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.5,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.3,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.1,lty=1,lwd=2,border='black')
points(0,0,col='red',cex=2,pch=4)
for (i in 1:35){
points(runif(1,0.3,0.5),runif(1,3.5,5.5),col='blue',cex=1,pch=19)
}
```
## A dart target, with the red cross representing the true parameter value
```{r echo = FALSE}
plot(0,0,type = "n", xlim = c(-1.4,1.4), ylim = c(-10,10),axes=F,xlab='',ylab='',main = 'Unbiased but imprecise')
draw.circle(0,0,radius=0.7,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.5,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.3,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.1,lty=1,lwd=2,border='black')
points(0,0,col='red',cex=2,pch=4)
for (i in 1:35){
points(runif(1,-0.3,0.3),runif(1,-3.5,3.5),col='blue',cex=1,pch=19)
}
```
## A dart target, with the red cross representing the true parameter value
```{r echo = FALSE}
plot(0,0,type = "n", xlim = c(-1.4,1.4), ylim = c(-10,10),axes=F,xlab='',ylab='',main = 'Unbiased and precise!')
draw.circle(0,0,radius=0.7,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.5,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.3,lty=1,lwd=2,border='black')
draw.circle(0,0,radius=0.1,lty=1,lwd=2,border='black')
points(0,0,col='red',cex=2,pch=4)
for (i in 1:35){
points(runif(1,-0.15,0.15),runif(1,-1.5,1.5),col='blue',cex=1,pch=19)
}
```
## The Maximum Likelihood Estimate (MLE)
* The MLE is the best guess set of parameter values for our given data
* \alert{But the chances of the true parameter values being close to the MLE is dependent on the amount of information in the data!}
## Binomial likelihood with increasing sample size
```{r, echo=FALSE}
lik.fun <- function(parameter) dbinom(x=3, size=10, prob=parameter,log=TRUE)
plot(lik.fun,0,1,xlab="probability of success (p)",ylab="log-likelihood(p)",main="",lwd=3)
lik.fun <- function(parameter) dbinom(x=30, size=100, prob=parameter,log=TRUE)
plot(lik.fun,0,1,add=T,col='blue',lwd=3)
lik.fun <- function(parameter) dbinom(x=300, size=1000, prob=parameter,log=TRUE)
plot(lik.fun,0,1,add=T,col='red',lwd=3)
abline(v=0.3,col='grey',lty=2)
legend('bottomright',c('3 out of 10','30 out of 100','300 out of 1000'), col=c('black','blue','red'),lty=1,lwd=2)
```
# Confidence intervals: A refresher
## Let's approach confidence intervals through simulations
```{r, message=FALSE, warning=FALSE, include=FALSE}
library(dplyr)
library(ggplot2)
set.seed(12345) # try different values
```
Imagine you are measuring the temperature of a cup of water 10 times but you have an old really bad thermometer.
The true temperature is 3 degrees Celsius and the standard deviation on the sampling error is 5.
```{r, message=FALSE, warning=FALSE}
# Simulate data:
mu <- 3
sigma <- 5
n <- 10
y <- rnorm(n = n, mean = mu, sd = sigma)
y
```
## Apply linear regression
We will estimate a mean temperature by fitting an intercept only linear regression model:
```{r, message=FALSE, warning=FALSE,collapse=TRUE}
m <- lm(y~1)
library(broom)
tidy(m)
confint(m)
```
## Let's illustrate what those confidence intervals really represent.
* Imagine you went outside 20 times and each time you measured the cup of water 10 times. Then you fitted a linear regression model with an intercept only each time and plotted the confidence intervals.
```{r, echo=FALSE, message=FALSE, warning=FALSE}
N <- 20
sim_ci <- NULL
for (i in 1:N){
y <- rnorm(n = n, mean = mu, sd = sigma)
m <- lm(y~1)
ci <- confint(m, level = 0.95)
sim_ci <- rbind(sim_ci,data.frame(l = ci[1], u = ci[2], y = y, i = i))
}
```
* 19 times out 20 (95%) the 95% confidence intervals should contain the true value.
## Does that look approximately correct?
```{r, echo=FALSE}
sim_ci %>%
filter(i <= 10) %>%
ggplot(aes(1, y)) +
geom_point(alpha = 0.2) +
geom_hline(aes(yintercept = l)) +
geom_hline(aes(yintercept = u)) +
geom_hline(yintercept = mu, colour = "red") +
labs(x = "", y = "") +
facet_wrap(~i, ncol = 5, scales = "free") +
xlim(0.99, 1.01) +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
```
## Does that look approximately correct?
```{r, echo=FALSE}
sim_ci %>%
filter(i > 10) %>%
ggplot(aes(1, y)) +
geom_point(alpha = 0.2) +
geom_hline(aes(yintercept = l)) +
geom_hline(aes(yintercept = u)) +
geom_hline(yintercept = mu, colour = "red") +
labs(x = "", y = "") +
facet_wrap(~i, ncol = 5, scales = "free") +
xlim(0.99, 1.01) +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
```
Confidence intervals are just \alert{one realization} of a theoretically repeated experiment.
## Likelihood key facts
* The likelihood is \alert{the probability of observing a (fixed) dataset given a set of parameter values} (to be estimated)
* Maximum likelihood theory provides \alert{estimates with optimal properties}: unbiased, minimal variance and normally distributed (asymptotically)
* The \alert{rate of change of the likelihood} around the MLE is an indication of our confidence in the estimated parameter values
* Use \alert{confidence intervals to capture uncertainty} surrounding MLEs
* Likelihood functions \alert{can get very complicated!}
## Textbooks
```{r, out.width = '10cm',out.height='7.5cm',fig.align='center',echo=FALSE}
knitr::include_graphics('img/textbooks1.png')
```
# This Class
## On our plate
* Distributions and likelihoods
* \alert{Hypothesis testing and multimodel inference}
* Introduction to Bayesian inference
* Generalized Linear Models (GLMs)
* Generalized Additive Models (GAMs)
* Mixed Effect Models
## Hypothesis testing: Rationale
The problem:
> Suppose a coin toss turns up $k = 12$ heads out of $N = 20$ trials.
Can we say that the coin toss is fair? Do we get more heads than expected (assuming the coin toss is fair)?
## Hypothesis testing: Rationale
1. \alert{Define the null and alternative hypotheses}.
The null hypothesis is usually the one that represents the less complicated explanation of the real world
* $H_0$: the coin toss is fair
* $H_1$: the coin toss is unfair, we get more heads or tails than expected
## Hypothesis testing: Rationale
2. \alert{Construct a sampling distribution for the estimator under $H_0$}
* The number of heads $X$ is a Binomial distribution with parameter $p$
* Under $H_0$, we have $p = p_0$ with $p_0=0.5$ if the coin toss is fair
* Under $H_1$, we have $p \neq p_0$