-
Notifications
You must be signed in to change notification settings - Fork 4
/
modelling_mondays.qmd
3294 lines (2127 loc) · 130 KB
/
modelling_mondays.qmd
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: "Modelling Mondays"
author: "Argyris Stringaris"
date: "05-06-2024"
format:
html:
toc: true
toc-depth: 3
toc-title: Table of contents
editor: visual
---
# Week 1: The Likelihood Function
## Motivation
What is Data Generating Process (DGP) and what is a likelihood function?
Typically, we think of a DGP as a mathematical formula that gives rise to a distribution. For example, the IQ curve can be generated through the Gaussian, named after Karl Friedrich Gauß--very much worth reading about also in the novel The Measuring of the World, by Kehlmann (where the parallel lives of Gauß and Humboldt are presented).
![](Carl_Friedrich_Gauss_1840_by_Jensen.jpg)
![](measuring_the_world.jpg)
But in a more abstract way, the question is, what are the mechanisms through which a set of data are generated, be it voting patterns, brain data or league games.
Consider, for example, a sample of the general population filling in a questionnaire about depression. Figure 1a. shows a typical pattern, that of a right-skewed truncated distribution. The "mechanism" that gives rise to the right skew is the fact that there are far more people without many symptoms and hence many people close to the zero mark. It is also truncated because scores can't go below zero and can't go above the max of the sum of the scale. By contrast, Figure 1b, shows the depression scores of a clinical population.
```{r echo = F, warning = F, message = F }
library(stevemisc)
library(tidyverse)
samples <- c(10^2, 10^3, 10^4, 10^5, 10^6, 5*10^6, 10*10^6)
mean_a <- 4.9
sd <- 4.49
mean_b <- 12
df_pop <- data.frame(
values = rbnorm(samples[4], mean_a, sd, 0, 26, round = TRUE, seed = 1974),
origin = rep("general population", samples[4])
)
df_comm <- data.frame(
values = rbnorm(samples[4], mean_b, sd, 0, 26, round = TRUE, seed = 1974),
origin = rep("clinical population", samples[4])
)
df_gen_vs_clin <- rbind(df_pop, df_comm)
df_gen_vs_clin %>%
ggplot(aes(x = values, fill= origin))+
geom_histogram(position = "identity", alpha = 0.4, bins = 40)+
ggtitle ("Two Data Generating Processes",
subtitle = "Score on a Depression Questionnaire")
```
In general, we always want to consider the DGP so as to:
a\) understand what gives rise to the data.
b\) mathematically describe (at least) how the data arise.
c\) estimate parameters (related to b)
d\) simulate the process to study it better.
## The omniscient person: knowing the DGS and the correct parameter.
This is someone who knows the function and its probability, is certain about the DGP. Let's say that they know that they are dealing with the normal distribution, which is formalised as:
$$
f(x | \theta) = \frac{1}{\sqrt{2\pi\sigma^2}} \cdot e^{-\frac{(x - \theta)^2}{2\sigma^2}}
$$ {#eq-1}
where, *x* is the point of interest of the probability density function, $\theta$ is the mean (location parameter) of the normal distribution, and $\sigma$ is the standard deviation (spread parameter).
```{r echo = F, warning = F, message = F}
# this is a function for the pdf, you can get it through dnorm.
pdf_normal <- function(x, theta, sigma) {
density <- 1 / (sqrt(2 * pi * sigma^2)) * exp(-((x - theta)^2) / (2 * sigma^2))
return(density)
}
x <- seq(from = 40, to = 180,by = 1) #giving it a typical range for IQs
theta <- 100 # we know this as the mean
sigma <- 15 # the sd
pdf_value <- pdf_normal(x, theta, sigma)
df_values_and_parameter <- data.frame(x, pdf_value)
df_values_and_parameter %>%
ggplot(aes(x, pdf_value))+
geom_point()
# sum(pdf_value[x<100,]) #check what this sums up to
```
You will all recognise this as the standard IQ curve.
Please note from Equation 1 that here the point is that the situation is phrased as:
$$f(x | \theta, \sigma)$$
i.e. we ask what the probability is of obtaining these data given the parameters $\theta$.
The situation where you are certain about the correct parameter and only need to know the frequency of individual values or set of values is a very convenient one to be in. Often however, in the real world we may have an intuition about what the DGP might be but not know the parameter(s). That is when we ask about the likelihood.
## A real person: having data, intuiting the DGS, and not knowing the parameter.
Consider having collected some data, having some intuition about the DGS and needing to find out the parameter amongst a set of parameters.
This is a more likely situation which I will illustrate here by trying to recover the mean parameter from synthetic data.
For the moment it is safe to say that what were trying to do here is to invert the process above, i.e. what you do with the probability density function. Instead of asking what data are likely to occur given a parameter (such as the mean and sd) that you *already* know about, here you ask, what is the most likely parameter that has given rise to the data I have.
$$
L(\mu, \sigma^2 | x_1, x_2, \ldots, x_n) = \prod_{i=1}^{n} \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x_i - \mu)^2}{2\sigma^2}\right)
$$ {#eq-2}
Equation 2 states precisely that: what is the likelihood of this mean and variance, given all these data points? Equation 2 on the right-hand side contains the PDF, as above, but what it says is that it takes the probability at each step and multiplies them altogether, this is what that giant Greek $\Pi$ stands for, the product.
Notice that when I tried this with fewer data points, I was able to get the likelihood, but when I increased them, I needed the natural log. Try it for yourself.
```{r echo = F, warning = F, message = F}
# I am using the above pdf to define the log-likelihood function
log_likelihood_normal <- function(x, theta, sigma) {
log_pdf <- log(1 / (sqrt(2 * pi * sigma^2)) * exp(-((x - theta)^2) / (2 * sigma^2)))
log_likelihood <- sum(log_pdf) # Log-likelihood for the entire dataset
return(log_likelihood)
}
#I could also have done this. Note what happens if you leave out the log...
# log_likelihood_normal <- function(mu, x) {
# log_pdf <- dnorm(x, mean = mu, sd = 15, log = TRUE) # Log of probability density function
# log_likelihood <- sum(log_pdf) # Log-likelihood for the entire dataset
# return(log_likelihood)
# }
#
# I am making synthetic iq data
set.seed(1974)
data <- rnorm(1000, mean = 100, sd = 15)
# log likelihood for the different mean values
mu_values <- seq(40, 160, by = 0.1) # Range of mu values to test
log_likelihood_values <- sapply(mu_values, function(mu) log_likelihood_normal(data, mu, 15))
# This gives me the MLE
mle <- mu_values[which.max(log_likelihood_values)] # close to 100!
df_log_likelihood <- data.frame(mu_values, log_likelihood_values)
df_log_likelihood %>%
ggplot(aes(x = mu_values, y = log_likelihood_values))+
geom_point()+
geom_vline(xintercept = mle, colour = "red")+
ggtitle("A Likelihood Function for IQ")+
ylab("Log-Likelihood")+
xlab("Means IQ points")
```
## Likelihood for the linear regression model
Now let's turn to the simple linear regression model. Let's start by asking how to think formally of the data generating mechanism of any linear model. It should be a
$$
y_i = \beta_0 + \beta_1 x_i + \epsilon_i
$$ {#eq-5}
where, $\epsilon_i$ follows a normal distribution with mean zero and variance $\sigma^2$
$$
L(\beta_0, \beta_1 | x_1, y_1, x_2, y_2, \ldots, x_n, y_n) = \prod_{i=1}^{n} f(y_i | \beta_0 + \beta_1 x_i)
$$ {#eq-6}
where $$f(y_i | \beta_0 + \beta_1 x_i) $$ {#eq-7} is the probability density function (PDF) of the normal distribution with mean $( \mu_i = \beta_0 + \beta_1 x_i )$ and constant variance $sigma^2$
To demonstrate this, I will first create synthetic data
```{r echo = F, warning = F, message = F}
# Some synthetic data
set.seed(1974)
n <- 100 # obs
x <- rnorm(n, mean = 5, sd = 2) # predictor
epsilon <- rnorm(n, mean = 0, sd = 1) # error
beta0 <- 2 # intercept arbitrary
beta1 <- 0.6 # slope also arbitrary
y <- beta0 + beta1 * x + epsilon # simulate the dependent variable
# Define the likelihood function for simple linear regression
stan_data_slope <- function(beta0, beta1, x, y) {
mu <- beta0 + beta1 * x # predicted values
log_likelihood <- sum(dnorm(y, mean = mu, sd = 1, log = TRUE)) # log-likelihood i have used # dnorm to save space, could have equally used the spelt out function that I created above
return(log_likelihood)
}
# The log-likelihood for different values of beta0 and beta1 REMIND ME TO TELL YOU ABOUT THE #PLAUSIBLE RANGE!
beta0_values <- seq(0, 4, by = 0.1)
beta1_values <- seq(0, 1, by = 0.01)
log_likelihood_values <- outer(beta0_values, beta1_values, # the outer function allows me to #have a vector of the two parameters, which you then pass each through the vectorised #function. This can be mind-boggling and I have created below an example with a simpler input #and function
Vectorize(function(b0, b1) stan_data_slope(b0, b1, x, y)))
# The MLE for beta0 and beta1
max_indices <- which(log_likelihood_values == max(log_likelihood_values), arr.ind = TRUE)
mle_beta0 <- beta0_values[max_indices[1]]
mle_beta1 <- beta1_values[max_indices[2]]
# Plot log-likelihood surface A PAIN!
# library(plot3D)
# persp3D(beta0_values, beta1_values, log_likelihood_values, xlab = "Beta0", ylab = "Beta1", zlab = "Log-Likelihood",
# main = "Log-Likelihood Surface for Simple Linear Regression")
# points3D(mle_beta0, mle_beta1, max(log_likelihood_values), col = "red", pch = 16)
#
```
In the code chunk below, I explain how the outer product and vectorisation works.
```{r warning = F, message = F , echo = F}
# Show the above with a simple function
simple_function <- function(a, b) {
return((a + b)^2)
}
# Create input vectors
input_vector_a <- c(1, 2, 3)
input_vector_b <- c(10, 20, 30)
# Apply the function to all combinations of elements from the input vectors
result_matrix <- outer(input_vector_a, input_vector_b, Vectorize(simple_function))
```
# Week 2: The Binomial Distribution
Before we move over to more complex models, let's consider the binomial or Bernoulli distribution. Here are two situations. In the first one, you are a Creator (let's say a game creator, rather than The Creator); in the other you are a detective.
## The binomial from a creator's point of view.
Let us assume that you are trying to create a game for which you must create sequences of binary events, let's say decisions between a state *H* and a state *T*. Basically, you want either of these two to appear with a probability that is on average $\pi = 0.5$ i.e. a 50% chance of appearing.
I want to take us back to something which whilst obvious, is often forgotten, namely that probabilities are things that we can understand "in the long run".
Here is what I mean. The way to create the game above is to invoke the binomial distribution. This is the following:
$$f(k;n,p) = \binom{n}{k} p^k (1-p)^{n-k}
$$ {#eq-3} where $\binom{n}{k}$ is the binomial coefficient (will explain this) and then come the probabilities.
Let's explain this. The binomial coefficient, basically says: if I have *n* objects and want to choose *k* of them, how many ways can this be done. Think of the following example. I have the letters ABCD; how many ways are there to combine two letters (sequnce doesn't matter, e.g. AB = BA) There are 6 possible ways: AB AC AD BC BD CD to play around with it, look at the code below.
```{r echo = F, warning = F, message = F}
some_objects <- c("blue", "red", "green", "black") # this the total set of possible objects, four colours in this case.
n <- length(some_objects) # here I just get the total number of colours
k <- 0: n # here I create the vector of possible numbers to choose, anything from nothing to the maximum, i.e. 0,1,2,3,4
how_many_ways <- choose(n, k) # this now gives us the number of ways that k objects can. be chosen out of n, play around with it and the above numbers
ways_to_choose <- paste("We have" , how_many_ways , "way(s) to choose", k , "objects out of", n)
print(ways_to_choose)
```
In Equation 3, this quantity is then multiplied with the product of $p^k$ *x* $(1-p)^{n-k}$ . This product is a sequence of possible events of success and failure, for a probability *p* . If you substitute numbers between 1 and, say, 4 (representing possible outcomes in 4 coin tosses) into them, you would get
$p^1$ *x* $(1-p)^{4-1}$
$p^2$ *x* $(1-p)^{4-2}$
$p^3$ *x* $(1-p)^{4-3}$
$p^4$ *x* $(1-p)^{4-4}$
Each of these sequences is then multiplied with the number of ways k objects can be chosen out of n total objects (e.g. the number of 4 times Heads in 10 throws).
A priori, which one of these outcomes would you expect to be more likely for a fair coin?
```{r echo = F, warning = F, message = F}
p <- 0.5
n <- 4
k <- 1:4
the_product<-0
the_ways_to_choose <- 0
multipl_the_two <- 0
outcomes <- 0
for(i in 1:n){
the_product[i] <- p^k[i] * (1-p)^(n-k[i]) # p^k*(1-p)^(n-k)
the_ways_to_choose[i] <- choose(n, k[i]) # the coefficient of choosing k items from n
multipl_the_two <- the_product*the_ways_to_choose # this is the formula
}
multipl_the_two # these now are the probabilities for each k-value, e.g. that we have 1, 2, 3 or four times Heads.
dbinom(1:4, 4, 0.5) # check whether what I have done above fits with what the R inbuilt function would give you
# play around with the dice
```
### Exercise 1.1
Modify the above code to create a game where a coin is tossed 100 times.
a\) Estimate the probabilities for each possible outcome, *k* and store in vector.
b\) Find the outcome, *k* with the maximum probability
c\) Plot all possible outcomes against their probabilities.
d\) check against the standard inbuilt R function
```{r echo = F, warning = F, message = F}
p <- 0.5
n <- 100
k <- 1:n # these are all the possible outcomes
the_product<-0
the_ways_to_choose <- 0
ultipl_the_two <- 0
outcomes <- 0
for(i in 1:n){
the_product[i] <- p^k[i] * (1-p)^(n-k[i]) # p^k*(1-p)^(n-k)
the_ways_to_choose[i] <- choose(n, k[i]) # the coefficient of choosing k items from n
multipl_the_two <- the_product*the_ways_to_choose # This is 1a
}
which.max(multipl_the_two) # this is 1b
plot(k, multipl_the_two) # this is 1c
#plot(k,dbinom(1:k, n, p)) # this is 1d
```
## The binomial for a detective
Now, suppose that you are the new detective in town. Your first case is that of "Nick the Shark", against whom there are several allegations of setting up fraudulent games. All you have to go by is a sheet of paper where all the outcomes of coin tosses were recorded by one of your informants. There were 271 outcomes that were Heads. You are now asked to find out whether the coin was fair or not.
You would ask for the help of the statistician, but they are all away at a big conference and you must appear in from of the judge who decides on whether the person can remain in detention or not.
The judge has an exceptional understanding of numbers for a legal person and asks you to prove to her your case that Nick is indeed a swindler, as you say, and not the upright occasionally gambling citizen that the defendant maintains that he is.
You spend the night, writing out all outcomes of the coin tosses, all 630 of them.
```{r echo = F, warning = F, message = F}
# Here I have created the likelihood function for a binomial
likelihood_binomial <- function(p, k, n) {
log_pmf <- log(choose(n, k) * p^k * (1 - p)^(n - k)) #PDF
log_likelihood <- sum(log_pmf) # just the product
return(log_likelihood)
}
k <-271 # Number of Heads in Nick's games
n <- 630 # Total number of coin tosses in Nick's game
# Calculate the likelihood for different values of p
p_values <- seq(0.1, 0.8, by = 0.01)
likelihood_values <- sapply(p_values, function(p) likelihood_binomial(p, k, n))
p_values[which.max(likelihood_values)]
# now plot
df_likelihood_binomial <- data.frame(p_values, likelihood_values)
df_likelihood_binomial %>%
ggplot (aes(x = p_values, y = likelihood_values))+
geom_point()+
ggtitle("Likelihood for Coin Tosses (Binomial Distribution)")+
xlab("probabilities")+
ylab("likelihood values")+
geom_vline(xintercept = p_values[which.max(likelihood_values)], colour = "red")+
geom_vline(xintercept = 0.5, colour = "blue")
```
This is impressive, you have evidence that the parameter that maximises the likelihood is different to 0.5. But the judge gets back at you and says: all this could easily be due to chance. After all, probability is a matter of doing "experiments in the long run"/
You are stunned at the unprecedented numeracy of a lawyer. She warns you that she will throw out the case and you will not get the arrest warrant issued due to insufficient evidence.
How can you demonstrate that the difference between the blue and the red line is not simply due to chance?
## The likelihood ratio test
The question is whether the likelihood at 0.5 (the null) is different to the likelihood at what you found to be the maximum likelihood in the observed data. What if you built the ratio of these two?
Indeed, the likelihood ratio test will allow you to answer the numerate judge's question. Because you have taken logs, the problem simplifies to a subtraction (logging ratios turns to a subtraction).
$$
\text{Likelihood Ratio} = -2*(\text{Log Likelihood}_{0.5} - \text{Log Likelihood}_{ML} )
$$ {#eq-4}
Now, you may wonder about what that *2* is doing there--not to worry about it for the moment, its presence allows you to assume this difference follows a chi-squared distribution. Don't forget the minus sign--you will need this as the values of the chi-squared distribution are all positive.
```{r echo = F, warning = F, message = F}
# first find the likelihood values at 0.5 and at the MLE
lr_0.5 <- df_likelihood_binomial[df_likelihood_binomial$p_values == 0.5,]$likelihood_values # this gets you the likelihood at the null, which is 0.5
lr_ML <- df_likelihood_binomial[which.max(df_likelihood_binomial$likelihood_values),]$likelihood_values # this gets you the likelihood at the max likelihood, its lowest value as per above
LLR = -2*(lr_0.5 - lr_ML) # this is the ratio you are looking for, the LLR = log likelihood ratio
df <- 1 # there is only one degree of freedom in this subtraction
alpha <- 0.05 # if you fancy this for a significance value
# now take a chi-squared distribution and find the critical value, i.e. the value on the chi-squared distribution that is significant for this alpha and df.
critical_value <- qchisq(1 - alpha, df)
# As you can see, the our LLR is much bigger than the critical value, hence it is significant. If you want to know the exact p-value
p_value_LLR_test <- pchisq(LLR, df, lower.tail = FALSE) # and this is your value
p_value_LLR_test
```
After this you can go back to the smart judge and convince her that your finding is very unlikely to have occurred by chance. To help you phrase things better to the judge, I have given you the exercise below.
### Exercise 1.2
a\) How exactly would you phrase your finding? How unlikely is it that Nick's games have occurred by chance?
b\) How would you construct standard errors and confidence intervals around those estimates? How would phrase the findings about the confidence intervals?
c\) Can you plot confidence intervals on the graph with the red and blue line?
Bonus Questions:
d\) You do a debrief with your team of detectives and informants. On this occasion, your informant had gathered 630 games. But what if he had sampled less, or more? Can you find out how many games he would have needed to have gathered for you to be able to demonstrate this difference to the judge (e.g. would 30 games be enough)? What do you call such a question in science?
## Small diversion: is coin tossing fair?
![](coin_tossing.jpg)
Check out this article here: <https://www.economist.com/science-and-technology/2023/10/15/how-to-predict-the-outcome-of-a-coin-toss>
# Week 3: Probability theory and The Bayes Theorem
## Of Men and Homicides
Before we revisit the above from a Bayesian perspective, we will need a small detour into probability theory.
About 90% of homicides in Europe are committed by men. How justified is it to say that "men are murderers". Think about this question also by replacing men with immigrant men, foreign men, or foreigners more generally. Think about what may be true in the aggregate (and generates stereotypes) and what is valuable at the individual level. Let's try to tackle this problem in a number of ways.
Let there be a population where,
the probability of homicide in a country be 2.3 in 100,000, i.e. $P(homicide) =$ 2.3\*10\^-5
the probability of being a man in that population be 50%, i.e. $P(man) =$ 0.5, and
the probability that if there is a homicide the perpetrator is a man be 90%, i.e. $P(man|homicide)$ = 0.9
The question is what is the probability that if I see a man on the street, he is a murderer, i.e. $P(homicide|man)$ .
Let's arrive at this step by step.
First, let's remind ourselves what the probability is of two events occurring together:
$$
P(A \cap B) = P(A) \cdot P(B) $$
This says that the co-occurrence of two events is the product of each event. However, this is only true if the two events are independent of each other, i.e. the occurrence of A has nothing to do with the occurrence of B. Is this the case here with men and homicides. What more general rule can we apply? Let's try to understand this graphically.
![](probability_set.jpg)
When you re-arrange this, you arrive at the very important following formula.
$$
P(A \cap B) = P(A \mid B) \cdot P(B)
$$
This formula allows you to calculate conditional probabilities if you have the joint ones and a prevalence, and vice versa. But this does not quite help us because we don't know the joint probability of homicides. For this we employ a trick. Re-arranged equation 9, also holds this way:
$$
P(A \cap B) = P(B\mid A) \cdot P(A)
$$
which then means that,
$$
P(A \mid B) \cdot P(B) = P(B \mid A) \cdot P(A)
$$ {#eq-10}
So, now you can estimate any of the two conditional probabilities, if you know the rest.
Let's apply this to our homicide example. Remember we need to estimate: $P(homicide|man)$
Therefore, rearranging and substituting our terms into Equation 10, we get:
$$
P(homicide\mid man) = \frac{P(man\mid homicide).P(homicide)}{P(man)}
$$ {#eq-11}
**CONGRATULATIONS: you have just entered the world of the Reverend Thomas Bayes! This is his theorem applied to homicides!**
As we will see further down, Bayes links back to the likelihood that we have been discussing and allows us to use priors and
### Exercise 3. 1
a\) Calculate conditional probability. b) Do so for a country like Brazil too, where the probability of homicide is about 10-fold higher. c) Comment on whether calling men, foreigners etc murderers may be considered stereotyping. What does it mean for individual prediction and what does it mean for public health and safety.
## Men, Homicides and marginal probabilities
Now let's look at the problem from a different angle. Let's create a table that captures the above in a representative sample, n = 100,000 of the population in Brazil, where the probability of homicide is about 20/10\^5, the gender ratio is assumed to be equal and the probability that a homicide is committed by a man is 0.9.
```{r echo = F, message = F, warning = F}
# Total obs
n <- 10^5
# Probabilities as above
p_male <- 0.5
p_female <- 0.5
p_homicide_total <- 20 / 100000 #this is the rate for Brazil
p_homicide_male <- 0.9 * p_homicide_total
p_homicide_female <- 0.1 * p_homicide_total
# simulate gender
genders <- sample(c("Male", "Female"), size = n, replace = TRUE, prob = c(p_male, p_female))
# Initialize homicide data
homicides <- rep("No", n)
# number of homicides committed by males and females
num_homicides_total <- round(p_homicide_total * n)
num_homicides_male <- round(p_homicide_male * n)
num_homicides_female <- num_homicides_total - num_homicides_male
# assign homicides to males and females
male_indices <- which(genders == "Male")
female_indices <- which(genders == "Female")
male_homicide_indices <- sample(male_indices, num_homicides_male, replace = FALSE)
female_homicide_indices <- sample(female_indices, num_homicides_female, replace = FALSE)
homicides[male_homicide_indices] <- "Yes"
homicides[female_homicide_indices] <- "Yes"
# the contingency table
contingency_table <- table(genders, homicides)
contingency_table
```
How do you calculate here $P(homicide|male)$ . Do it by hand. Do it also after substituting the European homicide probability given above. Do you get the same results?
```{r echo = F, message = F, warning = F}
num_males <- sum(genders == "Male")
num_male_homicides <- contingency_table["Male", "Yes"]
p_homicide_given_male <- num_male_homicides / num_males
paste("P(homicide | male) =", round(p_homicide_given_male,5))
```
Congratulations, you have just used a **marginal probability**, namely you summed the two outcomes for men, the Nos and Yess, and used them as denominators. This is fundamental in Bayesian statistics, as we shall see in the next few sessions. Here it is very simple. By the way, do it for girls too, what is it? It is an order of magnitude less, as you might expect, but both are very low. Ask yourselves, would gender be a good test to detect suicides?
## Homicides and Probability Trees
Now let's say that a new company comes and tells you that it has excellent sensitivity and specificity with 95% to detect the scent of a criminal. What conditional probabilities do sensitivity and specificity refer to?
Exactly, Sensitivity is $P(Test+|Criminal+)$ where + denotes having the characteristics (test positivity and being a criminal), i.e. how likely is the test to be positive if you are a criminal. The specificity is $P(Test-|Criminal-)$
Below is a probability tree. Where do you find the sensitivity and where do you find the specificity? And how do you estimate the reverse of the sensitivity? This is the key question, you are not that much interested in how the test performs in criminals, but rather **how the test behaves** in the population you are likely to encounter. This is given by $P(Criminal+|Test+)$ , i.e. the probability that you are indeed a criminal if you have a positive test. How do you calculate this and what is your denominator?
![](crime%20probability%20tree.jpg)
This quantity is fundamental to all medical tests and indeed all tests where you want to draw inferences about the goodness of the test in a given population. It is the **Positive Predictive Value and it is a Bayesian quantity.** Using very basic algebra and the rules derived above, I will try to demonstrate this in the picture below.
![](Image_1.jpeg)The two key equations here are:
$$
P(homicide+|test+) = \frac{P(test+|homicide+).P(homicide+)}{P(test+)}
$$ {#eq-12}
Notice the similarity of this equation with that of Equation 11. I have also added in red some nomenclature that we will be encountering very soon, in the next lesson. Now, as I have derived above, there is another way to derive the same quantity using the known properties of the sensitivity and specificity and the prevalence of the population, without needing any other information.
$$
P(homicide+|test+) = \frac{P(test+|homicide+).P(homicide+)}{sensitivity.P(homicide+) + (1-specificity).P(homicide-)}
$$ {#eq-13}
Look at the denominators of both Eq. 12 and 13. These are the marginal likelihoods (also called the evidence). They are cumbersome, but not nearly as complex as what we will be encountering soon, even for solving the same simple binomial problem that we had solved in the last lesson. Indeed, these denominators are often analytically intractable and require approaches such as MCMC algorithms.
We will come to all this.
Meanwhile, I am going to give you some extra code that allows you to play around with sensitivities, specificities, PPV, NPV, but also with the chances of having a disease if someone tells you that you have a negative test (always very important).
Try to understand the basic notion of the Bayesian theorem and apply it to various situations of interest to you, like medical tests, exam results etc. Next time we will pick up again the problem of Nick the Shark and play around with the Bayesian estimation of the finding.
# Week 4: Some more on crime and punishment
## Contingency tables and expected values (a little detour)
Before we delve into some Bayesian stuff, it may be good to remind ourselves of some very simple principles that would help us decide whether men are more likely to commit crimes according to common standards of significance.
Just to remind you, this was our contingency table:
```{r echo = F, warning = F, message = F}
contingency_table
```
How would you decide on whether the differences are "significant". You did come up with probabilities for this problem above for males and females. But how would you know that they differ?
We will treat this problem using a standard frequentist approach and then turn to a Bayesian answer later in our meetings. What we need to do is create expected values for each cell in the above example. What would you do?
First, you will need the marginals. There are three types of marginals, the row marginals, the column marginals, and the totals.
The command below gives you the row marginals.
```{r}
marginSums(contingency_table,1)
```
This one the column ones
```{r}
marginSums(contingency_table,2)
```
and here is the totals
```{r}
marginSums(contingency_table)
```
or to create the whole table do
```{r}
addmargins(contingency_table)
```
$P(gender == female \cap homicide = no)$ = $P(gender == female \mid homicide == no). P(homicide == no)$
$P(gender == female \cap homicide = yes)$ = $P(gender == female \mid homicide == yes). P(homicide == yes)$
$\sum P(females == yes |homicide)$
Can you think of a way to get expected values now?
There are two principle ways to think about it which are complementary. Either to think of the "rule of three" from primary school maths, or to think in a Bayesian (or rather generally more abstract) way about it. I will start with the simple way.
Let's start with Females who do not kill, how many would we expect? This is the top lefthand corner cell. We **observe** 50167 who have not committed murder and 2 who have. How many would we have expected in each of these two cells? How do we use the term expected? In the sense that ignore the observed column values and say, well there are 50169 (the row total value) overall in 10\^5 people (the overall total). How many would there be in the 99980 (the No column, in which the first cell is situated). It follows that we obtain the **expected value** by doing $50169*99980/(10^5)$ which is 50159 after rounding.
If you do the same for each one of the cells, you get the following table of **expected** values.
```{r}
exp_table <- chisq.test(contingency_table)$expected
exp_table
```
compare the two tables, what do you see?
How can you formalise this into a statistical answer? This will be an exercise for next time (see below). For the moment, and in the interest of abstracting, what exactly did I do here when I used the rule of three?
Let's write out some simple operations in fancy terms.
What is the probability of being female and not being a murderer on the basis of the observed data?
$$
P(gender == female\cap homicide == no) = 50167/10^5 = 0.5017
$$ {#eq-14}
But, let's go even more fancy, let's apply the Bayesian theorem and the relationship between joint and conditional probabilities.
$$
P(gender == female \cap homicide == no) = P(gender == female |homicide == no).P(homicide == no)
$$ {#eq-15}
This gives us the same result as you can verify by multiplying the two fractions: 50167/99980 x 99980/10\^5.
This is a bit ridiculous and a near tautology, but humour me for a bit. What if I asked you what the following quantity is (which is the equivalent of Equations 6.8 and 6.9 in the Farrell and Lewandowsky book:
$$
P(gender == female) = \sum_{\theta} P(\text{female} \mid \text{homiicide}) \cdot P(\text{homicide})
$$ {#eq-16}
You needn't worry of course, because all you have to do is to calculate eq-16 is to add eq-15 and eq 17 below (which is its counterpart, the cell right next to it, i.e. murdering females.
$$
P(gender == female \cap homicide == yes) = P(gender == female |homicide == yes).P(homicide == yes)
$$ {#eq-17}
Which gives you: (2/20\*20/10\^5) and is the same as doing the following simpler calculation.
$$
P(gender == female|homicide == yes) = 2/10^5 = 2x10^-5
$$ {#eq-18}
Now, all you have to do is add the results of
Indeed, when you try to add the results of summing eqs 15 and 17, you get to the marginal probability, which is all that equation 18 is asking you to do, except in fancy formalism:
(50167/99980\*99980/10\^5) = 0.50169 which is the same as what you would get if you simply divided the marginal for gender with the total i.e. 50169/10\^5
**PHEW!**
Does all this make sense? It is quite simple but can be mind-boggling.
Here is an exercise to consolidate expected values, we will follow up with the Bayesian stuff below.
### Exercise 4.1
*Once you have solved this exercise, you may get a fundamental insight about model evaluation, at least I did when I grasped this.*
a\) look at the table above with the observed values, let's call this table O_table and also look at the one with the expected values E_table. Try to conceive of them as locations on some imaginary map. All those numbers are nothing but locations on that multi-dimensional map. Indeed, each table is a matrix and a matrix can be thought of as a location in a space that has the matrices dimensions. The question arises then: how far away is O_table from E_table? What simple mathematical operation would allow you to answer this question?
b\) how can you tweak that simple mathematical operation to calculate on the distance.
c\) if you want to do the statistical estimation you will need some extra tools. Hint: what is a common way, e.g. used in simple regression estimation to get rid of annoying signs (positive, negative, without taking the absolute though)? another hint: you will need a distribution for deciding.
## Back to Bayes and meeting the beta distribution
From the discourse above, we need to remember equation 17, which I am writing here in its general form:
$$
P(y) = \sum_{\theta} P(\text{y} \mid \theta) \cdot P(\theta)
$$ {#eq-19}
This is the broad definition of the marginal likelihood and it is going to pop up very often. Equation 20 is simply its instantiation for continuous variables
$$
P(y) = \int_{\theta} P(\text{y} \mid \theta) \cdot P(\theta)d\theta
$$ {#eq-20}
Then of course the fundamental Bayesian equation is written as:
$$
P(\theta\mid y) = \frac {P(y \mid\theta ). P(\theta)}{\sum_{\theta} P(\text{y} \mid \theta) \cdot P(\theta)}
$$ {#eq-21}
or, for continuous quantities,
$$
P(\theta\mid y) = \frac {P(y \mid\theta ). P(\theta)}{\int_{\theta} P(\text{y} \mid \theta) \cdot P(\theta)d\theta}
$$ {#eq-22}
IMPORTANT: $P(\theta\mid y)$ is the posterior distribution, it is what every Bayesian analysis strives for.
I will skip the chapter on analytic methods for obtaining posteriors in the book in favour of a more conceptual understanding of the beta distribution.
You will all know about the debate between Bayesians and Frequentists. It has been raging for years and it usually focuses on the issue of the **priors** and whether Bayesians are unduly **subjective**. Indeed, Bayesians argue that when you try to make a statement about data, you ought to take prior knowledge into account. Perhaps more importantly, they extend the argument to say, well, you should actually update your model as new knowledge accumulates! Only in this way will you be able to be fair to the state of the world.
I won't go into the various arguments, except to say that even frequentists make a lot of decisions that require scientific **judgement**. The most notable one is the likelihood model that we choose. As we have seen, this is key to all modelling of data. Bayesians would say that their approach provides a principled way of assessing the probability of parameters but also of models. How? We shall see below. I have added some materials about voting patterns and confidence intervals that you may want to study.
For the moment, let's revisit, Nick the gambler.
How would you go about evaluating his honesty in a Bayesian way?
You remember that we used the binomial distribution as our likelihood model to estimate the likelihood of what Nick came up with.
For this let's turn to the beta distribution and highlight some interesting features.
I will start at the end, with a re-writing of the equation 6. 24 in the book for obtaining the posterior distribution of a coin toss with *n* tosses and *k* heads:
$$
P(\theta \mid k,n) = beta(\theta|\alpha + k, \beta + n -k)
$$ {#eq-23}
This basically says that if you toss a coin and want to use a Bayesian approach (and you choose as most Bayesians would) the beta distribution as a prior, all you have do is add something to those priors!
That seems super simple, but requires a lot of maths to arrive at. We will discuss all this at the next lesson. You may want to look here until then: <https://www.statlect.com/probability-distributions/beta-distribution>
But let's start with some basics.
Let's get an intuition for the beta. I am writing out its probability density function:
$$
f(x; \alpha, \beta) = \frac{x^{\alpha - 1} (1 - x)^{\beta - 1}}{B(\alpha, \beta)}
$$ {#eq-24}
We can glean that it has bits that look like the binomial in the numerator (and actually also in the denominator). We will delve into this next time.
For the time being let's play around with the beta distribution for different values of its two parameters. I am using the code below.
```{r echo = F, warning = F, message = F}
# i am defining the alpha and beta first
alpha <- .5
beta <-.5
# and the theta, i.e. the possible values of the toss
theta <- seq(0, 1, length.out = 1000)
prior_dist <- dbeta(theta, alpha, beta)
plot(theta, prior_dist)
```
Let now return to Nick... Play around with the priors by tuning the $\alpha$ and $\beta$ to various values and see what happens.
```{r echo = F, warning = F, message = F}
# Parameters
alpha_prior <- 1 #play around with this and the the beta
beta_prior <- 1
heads <- 271 # remember from above?
tosses <- 635
# Posterior parameters, see formalism above
alpha_post <- alpha_prior + heads
beta_post <- beta_prior + (tosses - heads)
# getting very fine grained with the beta to emulate continuity
theta <- seq(0, 1, length.out = 1000)
# Getting the prior and posterior distribution
prior_dist <- dbeta(theta, alpha_prior, beta_prior)
posterior_dist <- dbeta(theta, alpha_post, beta_post)
# Creatjng a long dffor plotting
df <- data.frame(
theta = rep(theta, 2),
density = c(prior_dist, posterior_dist),
Distribution = rep(c("Prior",
"Posterior"),
each = length(theta))
)
# Plot the prior and posterior distributions
df %>%
ggplot(aes(x = theta, y = density, color = Distribution, fill = Distribution)) +
geom_line() +
geom_area(alpha = 0.3, position = "identity") +
scale_y_continuous() +
labs(title = "Prior and Posterior Distributions",
x = "Theta (Probability of Heads)",
y = "Density") +
theme_minimal() +
theme(legend.position = "top") +
annotate("text", x = 0.25, y = 10, label =
paste0("Prior parameters:", "\nalpha = ", alpha_prior, ", beta = ", beta_prior))
# and back to our original question, what is the maximum value for the parameter?
theta[which.max(posterior_dist)]
```
Now what do you do with this information? Can you get confidence intervals? Yes!
What can you with these data, can you use them for prediction of future tosses.
### Exercise 4.2
a\) What is your understanding of what Ipsos, the polsters are saying here. Check out page 3, does it make sense?
<https://www.ipsos.com/sites/default/files/2017-03/IpsosPA_CredibilityIntervals.pdf>
b\) Can you see the relationship with this paper?
<https://www.tandfonline.com/doi/pdf/10.1080/01621459.2018.1448823?casa_token=phCtUIGpXcsAAAAA:TnbmBljQ5CaMfCreH_qxMLeIvdEKpJD_tTDPEE0cYK3a_-q0JBHYb3CUqkKHzf2V-gBYW64r5nEfyQ>
# Week 5: Self Study
# Week 6: Inference in Bayes through sampling.
This week we will try to familiarise ourselves with the notion and practicalities of sampling from the posterior. We are going to make small steps into this as it can become quite complex and is probably best revisited as the practical need arises (and it will indeed come up a lot in what we do).
## Why use sampling?
Notice the denominator of Equation 22, also called the evidence or the total space of the . Such an integral can be fairly simple, so that mere mortals like ourselves might stand a chance to solve analytically. But it can become quite complex, some times so complex that even evolved machines need help and special tricks to solve. But that does not matter and the reason is that we can make some reasonable assumptions that will help us arrive at knowledge about our parameters of inference in any given model.
This week, we will discuss one form of sampling, namely sampling from the posterior. We will assume that we have arrived at a posterior and will sample from it. It is to demonstrate the principle of sampling. We will only allude to what will become our main engine to support our Bayesian inference, namely Monte Carlo methods and chiefly the Metropolis-Hastings algorithms. We will however try to use today's example to fit our first models in Stan a probabilistic programming languages and brms, a package in R that talks to Stan.
## Some simple sampling in the case of Nick
The simple sampling from the posterior comes from chapter 3 of the McElreath book, Rethinking Statistics–a great resource by the way.
Let's consider the example of Nick the gambler again. We remember 271 heads out of 630 tosses was what our detective learnt about Nick's gambling games. In chpaters 2 and 3 we looked a lot at the likelihood, which as we recall is represented by the binomial probability density function. Please do refer to the formalisms above; here I will only remind us that we can use the dbinom function in base R for it. Let's then build a Bayesian model as we did above, in Week 4.
This code below generates the posterior distribution.
```{r }
n_heads <- 271
n_tosses <- 630
possible_prob_values <- seq(from = 0 , to = 1, length.out = 10^3) # these are the values that our parameter for the probability takes
likelihood <- dbinom(n_heads, n_tosses, prob = possible_prob_values) # our likelihood
prior <- rep(1: length(possible_prob_values)) # this prior is uniform, corresponds to a beta(1,1)
Bayes_numerator <- likelihood*prior # this is the numerator of Eqs 21 and 22.
posterior <- Bayes_numerator# /sum(Bayes_numerator) # the outcome of Eqs 21 and 22.
```
For me the simplest way of understanding what is going on is the following: to what value of the parameters (i.e. probabilities) does the maximum value of the posterior correspond to? I plot this here.
```{r}
plot(possible_prob_values, posterior)
```
You can also ask in the way we have before
```{r}
possible_prob_values[which.max(posterior)]
```
This number is very close to what we got when we did the maximum likelihood (which should be no surprise, since we used flat priors.
To illustrate that this can also be achieved through a draw 1000 values out of the posterior.
```{r}
sampled_posterior <- sample(possible_prob_values, # the parameter values to sample from
posterior, # these are the probabilities that we input
size = 10^3, # the size of it,
replace = T # got to do this
)
plot(density(sampled_posterior))
```
Now this may not sound trivial, but you just did your first sampling from the posterior...
### Exercise 6.1
a) Find the values of mean, median, mode and max of the sampled posterior. What do you observe?
b) Instead of sampling from the posterior, sample from the Bayes numerator.
c) Use the sample from (b) to re-run (a), what do you observe?
d) Do (b) and (c) using the likelihood instead of the Bayes numerator.
e) Find the 95% intervals–what would you call those intervals?
Here is a little pointer for 5.1.e
![](confidence_intervals_McElreath.jpg)
## Simplifying posterior sampling
The general point though of Exercise 5.1 is to illustrate something that the Farrell & Lewandowski book mentions in chapter 7, namely equation 7.1. It states that all we need to know to do the sampling is the Bayes numerator, i.e. the likelihood multiplied by the prior. This is because the evidence, i.e. the denominator (i.e. the marginal likelihood) is a constant in relation to this quantity. Therefore, equation 22:
$$
P(\theta\mid y) = \frac {P(y \mid\theta ). P(\theta)}{\int_{\theta} P(\text{y} \mid \theta) \cdot P(\theta)d\theta}
$$
can be reduced to:
$$
P(\theta\mid y) \propto P(y \mid\theta ). P(\theta)
$$ {#eq-25}
Where $\propto$ means proportional to, the posterior is proportional to the Bayes numerator, i.e. the likelihood times the prior.
Therefore, we can use algorithms like the Metropolis-Hastings, which we will talk about in more detail in the next few weeks, to arrive at inferences.
For this week though, let's estimate the Nick problem using hardcore Bayesian models...
First off, with brms, the very useful package: *Bayesian Regression Models Using Stan*, an R package that is structured like lme, but allows you to fit a wide range of linear and non-linear models. It uses an Hamilton Monte Carlo estimator, based on similar principles to MHMC that we will be seeing later.
Here is some brms code to run the Nick model.
```{r results='hide', warning=F, message=F}
library(brms)
brm(data = list(nheads = 271),
family = binomial(link = "identity"),
nheads | trials(630) ~ 0 + Intercept,
# we are using a flat prior--like the uniform above.
prior(beta(1, 1), class = b, lb = 0, ub = 1),
iter = 2000, warmup = 500, # we will discuss this in more detail above.
seed = 3)
```
### Exercise 6.2
a\. go through the code above line by line. What is the model, see "nheads \| trials(630) \~ 0 + Intercept"