-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-Statistical-models-for-Non-Life-Insurance-Pricing.Rmd
3484 lines (2746 loc) · 190 KB
/
02-Statistical-models-for-Non-Life-Insurance-Pricing.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
---
output:
bookdown::word_document2: default
bookdown::pdf_document2:
template: templates/brief_template.tex
bookdown::html_document2: default
documentclass: book
bibliography: references.bib
editor_options:
chunk_output_type: console
---
```{r echo=FALSE}
library(knitr)
```
<!-- Needed for leaving space to the quote, * is for no indentation after title -->
<!-- \titlespacing*{\chapter}{0pt}{80px}{35pt} -->
# Statistical models for Non Life Insurance Pricing {#chap:models}
<!-- \minitoc --> <!--this will include a mini table of contents-->
<!-- \chaptermark{Statistical models for Non Life Insurance Pricing} -->
In this chapter we are going to illustrate some of the most widespread statistical models for technical pricing. For each model we are going to describe its benefits and drawbacks and in section \@ref(chap:considerations-on-models) we will compare them by discussing how they fit the pricing needs.
## Statistical Models
In this section we will start by describing the \ac{glm}, that is the most employed model in technical pricing today, to then present some of its advancements: the \ac{gam}, the Shrinkage estimators for \ac{glm} and the Bayesian \ac{glm}.
### Generalized Linear Models {#chap:glm}
The \ac{glm}s are widely illustrated in many statistics textbooks. Among them we refer to [@wuthrich-data-analytics], [@gigante2010tariffazione], [@azzalini1996statistical], [@davison2003statistical], [@james2013introduction], [@friedman2001elements] and [@portugues-predictive-modeling]. More details on the concepts described in this section are reported in appendix \@ref(chap:appendix-exp-family).
#### Linear Exponential Families {#chap:linear-exp-families}
One of the \ac{glm} assumptions is that the response variables belong to a _Linear Exponential Family_. In this section we are going to explain what a linear exponential family is and which distributions fit its definition.
```{definition, linear-exp-family, name = "Linear Exponential Family"}
A Linear Exponential Family $\mathcal{F}$ is a parametrical family of probability distributions with density function (or probability function in the discrete case) that can be expressed in the form:
$$
f(y; \theta, \lambda) = \exp{\left\{ \frac{y\theta-b(\theta)}{\lambda} \right\}} \ c(y,\lambda), \quad y\in \mathcal{Y}\subseteq\mathbb{R}
$$
where:
\begin{itemize}
\item $\theta\in\Theta\subseteq\mathbb{R}$ is called \textit{canonical parameter};
\item $\lambda\in\Lambda\subseteq]0, +\infty[$ is called \textit{dispersion parameter};
\item $b: \Theta \rightarrow \mathbb{R}$ is a real function called \textit{cumulant function};
\item $c: (\mathcal{Y}, \Lambda) \rightarrow [0, +\infty[$ is a real function;
\item $\Theta$ is a non degenerate interval, i.e. $\text{int}\Theta$ is not empty.
\end{itemize}
```
An exponential family $\mathcal{F}$ is characterized by the elements $\left( \Theta, b(\cdot), \Lambda, c(\cdot, \cdot) \right)$. By properly choosing the sets $\Theta, \Lambda$ and the functions $b(\cdot), c(\cdot, \cdot)$, it is possible to obtain many useful families.
It can be easily shown that the families Normal, Poisson, Gamma and Binomial are exponential families. In table \@ref(tab:exp-families) the characterizations for these exponential families are reported.
The distributions that belong to an exponential family have many useful properties. For example they are provided with all the moments and their moments can be obtained using the derivatives of the cumulative function $b(\cdot)$. If $Y$ is a random variable with distribution belonging to an exponential family $\mathcal{F}$ with parameters $\theta, \lambda$, its first two moments are:
\begin{align}
\label{eq:exp-fam-expected-value}
E(Y) & = b'(\theta) \\
Var(Y) & = \lambda b''(\theta)
\end{align}
As, within a specified family, the parameters $\theta$ and $\lambda$ determine a distribution, in practical problems the object of estimation will be the couple $(\theta, \lambda)$. In many problems it is natural to consider distributions from a linear exponential family where the dispersion parameter can be expressed as $\lambda = \frac{\phi}{\omega}$, where $\omega>0$ is a known _weight_ and $\phi>0$ is a parameter that we will keep calling _dispersion parameter_. In this case, the density of probability function depends on the parameters $\theta$ and $\phi$ and will be expressed as:
$$
f(y; \theta, \phi, \omega) = \exp{\left\{ \frac{\omega}{\phi} \left[y\theta - b(\theta) \right] \right\}} \ c(y, \phi, \omega), \quad y\in \mathcal{Y}\subseteq\mathbb{R}
$$
In this case the parameters $\theta$ and $\phi$ will be object of estimation, while $\omega$ is an already known value. As we will see later, this representation allows us to consider as known weights:
* the exposure $v$ in the Poisson distribution;
* the number of trials $n$ in the Binomial distribution.
#### Model assumptions {#chap:glm-assumptions}
Let's assume that, for $n$ statistical units, the observations
$$\mathcal{D} = \left\{ (\boldsymbol{x}_1, \omega_1, y_1), \dots, (\boldsymbol{x}_n, \omega_n, y_n) \right\}$$
are available, where $\boldsymbol{x}_i$ is a vector of explanatory variables determinations, $\omega_i$ is a known weight and $y_i$ is the response variable determination. $\boldsymbol{x}_i, \omega_i, y_i$ are all real numbers. The vector $\boldsymbol{y} = (y_1, \dots, y_n)^t$ is considered a determination of the response random vector $\boldsymbol{Y} = (Y_1, \dots, Y_n)^t$.
In \ac{glm} we assume that:
<!-- \begin{enumerate}[topsep=8pt,itemsep=4pt,partopsep=4pt,parsep=4pt] -->
\begin{enumerate}[itemsep=4pt]
\item The response variables $Y_1, \dots, Y_n$ are stochastically independent and with probability distribution belonging to a same linear exponential family; i.e. the probability distribution of $Y_i$ has density function (or probability function in the discrete case) that can be expressed as:
$$
f(y_i; \theta_i, \phi, \omega_i) = \exp{\left\{ \frac{\omega_i}{\phi} \left[y_i\theta_i - b(\theta_i) \right] \right\}} \ c(y_i, \phi, \omega_i), \quad y_i\in \mathcal{Y}\subseteq\mathbb{R}
$$
We highlight that only $\theta_i$ and $\omega_i$ depend on $i$, while the dispersion parameter $\phi$ is the same for all the observations.
\item The explanatory variables determinations vector $\boldsymbol{x}_i = \left(1, x_{i1}, \dots, x_{ip} \right)^t$ affects the probability distribution of the response variable $Y_i$ by the linear predictor:
$$
\eta_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \dots + \beta_p x_{ip}
$$
that is a linear function of the regression parameters $\boldsymbol{\beta} = \left( \beta_0, \beta_1, \dots, \beta_p \right)$.
\item The linear predictor $\eta_i$ is linked to the expected value of the response variable $\mu_i = E(Y_i)$ by the following relation:
$$
g(\mu_i) = \eta_i = \boldsymbol{x}_i^t \boldsymbol{\beta}
$$
where $g:\mathbb{R}\rightarrow\mathbb{R}$ is a monotonic function with continuous first and second derivatives. $g(\cdot)$ is called \textit{link function}.
\end{enumerate}
Often, the assumption 1 is called stochastic assumption, while the 2 and 3 are called structural assumptions.
Let's indicate with $\boldsymbol{X}$ the design matrix. The design matrix is the matrix in which each row $\boldsymbol{x}_{i\cdot}$ represents the vector of the explanatory variables for the observation $i$ and each column $\boldsymbol{x}_{\cdot j}$ represents the vector of the observations for the explanatory variable $j$. We also consider a column of 1s as first column, that is used to model the intercept of the linear predictor. Thus, $\boldsymbol{X}$ is a matrix $n\times(p+1)$. We assume, as it is common in actuarial datasets, that $n>p+1$. The design matrix is represented in figure \@ref(fig:design-matrix).
```{tikz, design-matrix, fig.cap = "Design Matrix $\\boldsymbol{X}$.", fig.ext = 'pdf', cache = TRUE, echo = FALSE, fig.align = 'center'}
\usetikzlibrary{arrows.meta, bending, matrix, positioning}
\pgfdeclarelayer{bg} % declare background layer
\pgfsetlayers{bg,main} % set the order of the layers (main is the standard layer)
%\usepackage{xcolor}
\definecolor{col1}{HTML}{F8766D} % hue palette
\definecolor{col2}{HTML}{00BFC4} % hue palette
%\definecolor{col1}{HTML}{8C0808} % Brick red
%\definecolor{col1}{HTML}{BD2027} % red
%\definecolor{col2}{HTML}{7F7F7F} % Grey
%\definecolor{col2}{HTML}{BFBFBF} % Light Grey
\begin{center}
\begin{tikzpicture}[node distance = 1mm and 0mm, baseline]
% Draw matrix
\matrix (M1) [matrix of nodes,{left delimiter=[},{right delimiter=]}]
{
$1$ & $x_{11}$ & $\dots$ & $x_{1j}$ & $\dots$ & $x_{1p}$ \\
$1$ & $x_{21}$ & $\dots$ & $x_{2j}$ & $\dots$ & $x_{2p}$ \\
$\vdots$ & $\vdots$ & $\ddots$ & $\vdots$ & $\ddots$ & $\vdots$ \\
$1$ & $x_{i1}$ & $\dots$ & $x_{ij}$ & $\dots$ & $x_{ip}$ \\
$\vdots$ & $\vdots$ & $\ddots$ & $\vdots$ & $\ddots$ & $\vdots$ \\
$1$ & $x_{n1}$ & $\dots$ & $x_{nj}$ & $\dots$ & $x_{np}$ \\
};
% Draw red vertical rectangle
\begin{pgfonlayer}{bg} % select the background layer
%\draw[red!60, very thick, fill = red!60, fill opacity = 0.2]
% (M1-1-4.north west) -| (M1-6-4.south east) -| (M1-1-4.north west);
\draw[col1, very thick, fill = col1, fill opacity = 0.2]
(M1-1-4.north west) -| (M1-6-4.south east) -| (M1-1-4.north west);
\end{pgfonlayer}
\node (ev) [below = 1cm of M1-6-4.south, align = center] {$\boldsymbol{x}_{\cdot j}$\\explanatory\\variable $j$};
\draw[col1, very thick,shorten >=1mm, -{Stealth[bend]}]
(ev.north) to (M1-6-4.south);
% Draw blue horizontal rectangle
\begin{pgfonlayer}{bg} % select the background layer
%\draw[blue!60, very thick, fill = blue!60, fill opacity = 0.2]
% (M1-4-1.north west) -| (M1-4-6.south east) -| (M1-4-1.north west);
\draw[col2, very thick, fill = col2, fill opacity = 0.2]
(M1-4-1.north west) -| (M1-4-6.south east) -| (M1-4-1.north west);
\end{pgfonlayer}
\node (obs) [right = 1cm of M1-4-6.east, align = center] {$\boldsymbol{x}_{i\cdot}$\\observation $i$};
\draw[col2, very thick,shorten >=1mm, -{Stealth[bend]}]
(obs.west) to (M1-4-6.east);
\end{tikzpicture}
\end{center}
```
We can then express the \ac{glm} structural assumptions in a matrix form as:
$$
\boldsymbol{g}(\boldsymbol{\mu}) = \boldsymbol{X} \boldsymbol{\beta}
$$
where $\boldsymbol{g}(\cdot)$ must be intended as the vectorial function that links every $\mu_i$ to $g(\mu_i)$.
$$
\begin{array}{cccc}
\boldsymbol{g}: & \mathbb{R}^n & \longrightarrow & \mathbb{R}^n \\
& \left(
\begin{matrix} \mu_1 \\ \vdots \\ \mu_n \end{matrix}
\right)
& \longmapsto &
\left(
\begin{matrix} g(\mu_1) \\ \vdots \\ g(\mu_n) \end{matrix}
\right)
\end{array}
$$
We assume the design matrix to be a full rank matrix, i.e. $\text{rank}(\boldsymbol{X}) = p+1$. This assumption corresponds to assuming that the columns of $\boldsymbol{X}$ are linearly independent.
The function $g(\cdot)$ can be chosen as any monotonic function with continuous first and second derivatives. Given a family $\mathcal{F}$, a common choice is its canonical link function that is defined as:
$$
g(\mu) = b'^{-1}(\mu)
$$
From \@ref(eq:exp-fam-expected-value) we obtain that, as $\mu = b'(\theta)$, choosing the canonical function corresponds to using $\theta$ as the linear predictor:
$$
\eta = g(\mu) = b'^{-1}(\mu) = \theta
$$
In table \@ref(tab:can-link-fun) the canonical link functions for the families already mentioned are reported.
#### Model fitting {#chap:glm-model-fitting}
The model depends on the parameters $\left(\boldsymbol{\beta}, \phi\right)$. Indeed, the parameters $\theta_i$ can be obtained by $\boldsymbol{\beta}$ as:
$$
\theta_i = b'^{-1}(\mu_i) = b'^{-1}(g^{-1}(\eta_i)) = b'^{-1}\left(g^{-1}\left(\boldsymbol{x}_i^t\boldsymbol{\beta}\right)\right)
$$
Therefore, fitting the model corresponds to estimating $\left(\boldsymbol{\beta}, \phi\right)$. The technique used in \ac{glm} is the _Maximum Likelihood_. Let's indicate with $L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)$ the model likelihood. We remind that the likelihood is a function of the parameters that maps $\left(\boldsymbol{\beta}, \phi\right)$ to the density (or probability in the discrete case) of the observed values $\boldsymbol{y}$ conditioned to the parameters $\left(\boldsymbol{\beta}, \phi\right)$
$$
\begin{array}{cccc}
L: & \mathbb{R}^{p+1} \times \Lambda & \longrightarrow & [0, +\infty[ \\
& \left(\boldsymbol{\beta}, \phi\right) & \longmapsto & f_{\boldsymbol{Y}}(\boldsymbol{y}; \boldsymbol{\theta}, \phi)
\end{array}
$$
The maximum likelihood estimates are the values $\left(\boldsymbol{\beta}, \phi\right)$ that maximize $L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)$. In practice, $\boldsymbol{\beta}$ are the parameters of interest, while $\phi$ is considered as a disturbance parameter. It is possible to show that conditioned to any $\phi$, the value for $\boldsymbol{\beta}$ that maximizes $L(\cdot, \cdot)$ does not depend on $\phi$. Therefore, $\boldsymbol{\beta}$ and $\phi$ can be estimated separately.
Let's indicate with $\tilde{\boldsymbol{\beta}}$ the maximum likelihood estimator for $\boldsymbol{\beta}$. Its determination $\hat{\boldsymbol{\beta}}$ is defined as:
\begin{equation}
\label{eq:max-lik-est}
\hat{\boldsymbol{\beta}} = \argmax_{\boldsymbol{\beta}\in\mathbb{R}^{p+1}}{L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)}
\end{equation}
Finding the values $\hat{\boldsymbol{\beta}}$ that maximize the likelihood corresponds to finding the values that maximize the log-likelihood $\ell\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right) = \log{\left(L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)\right)}$. For the independence hypothesis on $Y_1, \dots, Y_n$ we get:
\begin{align}
\nonumber
\ell\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right) & =
\log{\left(L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)\right)}
\\ \nonumber & =
\log{\left(\prod_{i=1}^{n}{\exp{\left\{ \frac{\omega_i}{\phi} \left[y_i\theta_i - b(\theta_i) \right] \right\}} c(y_i, \phi, \omega_i)}\right)}
\\ \label{eq:log-like} & =
\sum_{i=1}^{n}{
\left\{
\frac{\omega_i}{\phi} \left[y_i\theta_i - b(\theta_i) \right] + \log{\left(c(y_i, \phi, \omega_i)\right)}
\right\}
}
\\ \nonumber & =
\sum_{i=1}^{n}{\ell_i\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)}
\end{align}
The maximum value of $\ell\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)$ can be obtained by imposing all its partial derivatives equal to $0$:
$$
\frac{\partial \ell\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)}
{\partial\beta_j}
= 0, \quad \forall j\in\{0,1,\dots,p\}
$$
These equations can be solved with numerical methods, such as Newton-Raphson algorithm or its variant Fisher scoring. It is possible to show that Newton-Raphson algorithm corresponds to iteratively solving a weighted least squares optimization problem.
In the case with Normal response and identity link, the optimization problem \@ref(eq:max-lik-est) has an explicit solution:
$$
\hat{\boldsymbol{\beta}} = \left( \boldsymbol{X}^t \boldsymbol{X} \right)^{-1} \boldsymbol{X}^t \boldsymbol{y}
$$
A statistic that can be used to measure the goodness of fit of a model is the _Deviance_. It can be used by comparing the current model log-likelihood $\ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)$ with the _saturated model_ log-likelihood $\ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)$. The saturated model is the model with $n$ parameters, so a model where the expected values of the response variables $\mu_1, \dots, \mu_n$ are estimated with their observed values $y_1, \dots, y_n$. It is possible to show that $\ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right) \ge \ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)$. The closer $\ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)$ is to $\ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)$, the better the current model fitting is.
```{definition, deviance-def, name = "Deviance"}
Given the log-likelihood of the current model $\ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)$ and the log-likelihood of the saturated model $\ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)$, the \textit{Scaled Deviance} of the current model is defined as:
$$
S(\hat{\boldsymbol{\beta}}, \phi, \boldsymbol{y}) =
-2\left(
\ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)
- \ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)
\right)
$$
The \textit{Deviance} of the current model is defined as:
$$
D(\hat{\boldsymbol{\beta}}, \boldsymbol{y}) =
\phi \, S(\hat{\boldsymbol{\beta}}, \phi, \boldsymbol{y})
$$
```
In deviance notation $D(\hat{\boldsymbol{\beta}}, \boldsymbol{y})$, the parameter $\phi$ is not reported because the deviance does not depend on $\phi$. Indeed, from \@ref(eq:log-like) we get:
\begin{align*}
S(\hat{\boldsymbol{\beta}}, \phi, \boldsymbol{y})
& =
-2\left(
\ell\left(\hat{\boldsymbol{\beta}}, \phi; \boldsymbol{y}\right)
- \ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)
\right)
\\ & =
-2\left(
\sum_{i=1}^{n}{
\left\{
\frac{\omega_i}{\phi} \left[y_i\hat{\theta}_i - b(\hat{\theta}_i) \right] + \log{\left(c(y_i, \phi, \omega_i)\right)}
\right\}
}
\right.
\\ & \qquad \qquad -
\left.
\sum_{i=1}^{n}{
\left\{
\frac{\omega_i}{\phi} \left[y_i\theta_i^* - b(\theta_i^*) \right] + \log{\left(c(y_i, \phi, \omega_i)\right)}
\right\}
}
\right)
\\ & =
-2\left(
\sum_{i=1}^{n}{
\frac{\omega_i}{\phi}
\left\{
\left[y_i\hat{\theta}_i - b(\hat{\theta}_i) \right]
- \left[y_i\theta_i^* - b(\theta_i^*) \right]
\right\}
}
\right)
%
\\[12pt]
%
D(\hat{\boldsymbol{\beta}}, \boldsymbol{y})
& =
-2\left(
\sum_{i=1}^{n}{
\omega_i
\left\{
\left[y_i\hat{\theta}_i - b(\hat{\theta}_i) \right]
- \left[y_i\theta_i^* - b(\theta_i^*) \right]
\right\}
}
\right)
\end{align*}
In table \@ref(tab:deviance) the deviances for the families mentioned are reported.
As $\ell_{S}\left(\boldsymbol{\beta}^*, \phi; \boldsymbol{y}\right)$ does not depend on $\hat{\boldsymbol{\beta}}$, maximizing the likelihood in equation \@ref(eq:max-lik-est) is the same as minimizing the deviance, that can be seen as a _Loss Function_:
\begin{equation}
\label{eq:max-lik-est-deviance}
\hat{\boldsymbol{\beta}} = \argmin_{\boldsymbol{\beta}\in\mathbb{R}^{p+1}}{D(\boldsymbol{\beta}, \boldsymbol{y})}
\end{equation}
<!--
* Maximum likelihood
* Iteratively reweighted least squares
+ Newton-Raphson, Fisher scoring
* Modello saturo
* Deviance
+ Loss function. Optimization process
-->
We conclude this section by also mentioning that in practice it is possible to use the estimator $\hat{\beta}$ defined by the optimization problem \@ref(eq:max-lik-est) for a specific exponential family without assuming the distribution of the response variable to belong to that family. Basically, in these cases we just make assumptions on the first two moments of the response variable $Y$ and not on its full distribution. In these models the function $L\left(\boldsymbol{\beta}, \phi; \boldsymbol{y}\right)$ is called _Quasi-Likelihood_ and the function $D(\boldsymbol{\beta}, \boldsymbol{y})$ is called _Quasi-Deviance_.
For instance, if we fit our model by minimizing the loss function of the Poisson distribution, we are implicitly employing a Quasi-Likelihood model. If we are using the Poisson Likelihood, the model is also called _Quasi-Poisson_ model.
#### Variable effects {#chap:var-effects}
As we mentioned in section \@ref(chap:pricing-variables-encoding), the explanatory variables can be _quantitative_ or _qualitative_. In \ac{glm}s, if explanatory variables transformation terms aren't added to the linear predictor $\eta$, the variables effect on $\eta$ is linear. In figure \@ref(fig:expl-var-types) the effects of quantitative and qualitative variables are shown. The data is simulated from a \ac{glm} with Normal response and identity link.
(ref:expl-var-types-caption-latex) Explanatory variables types.
(ref:expl-var-types-caption-gitbook) Explanatory variables types, quantitative (top-left), qualitative (top-right), quantitative and qualitative without interaction (bottom-left) and quantitative and qualitative without interaction (bottom-right).
```{r, plot-quant-qual-build, echo = FALSE, cache = TRUE}
set.seed(42)
## Colors defined in index.Rmd
# col1 <- hue_pal()(2)[1]
# col2 <- hue_pal()(2)[2]
line_size <- 2
n <- 200
b0 <- 1
b1 <- 2
b2 <- 1
b12 <- -1
sigma <- .1
df1 <- tibble(x = runif(n = n, min = 0, max = 1)) %>%
mutate(mu = b0 + b1 * x)
df1$y <- rnorm(n = n, mean = df1$mu, sd = sigma)
df2 <- tibble(x = c(rep(0, times = n/2), rep(1, times = n/2))) %>%
mutate(mu = b0 + b2 * x)
df2$y <- rnorm(n = n, mean = df2$mu, sd = sigma)
df3 <- tibble(x1 = runif(n = 2*n, min = 0, max = 1),
x2 = c(rep(0, times = n), rep(1, times = n))) %>%
mutate(mu = b0 + b1 * x1 + b2*x2)
df3$y <- rnorm(n = 2*n, mean = df3$mu, sd = sigma)
df4 <- tibble(x1 = runif(n = 2*n, min = 0, max = 1),
x2 = c(rep(0, times = n), rep(1, times = n))) %>%
mutate(mu = b0 + b1 * x1 + b2 * x2 + b12 * x1 * x2)
df4$y <- rnorm(n = 2*n, mean = df4$mu, sd = sigma)
p_quant_qual_1 <- df1 %>%
ggplot(aes(x = x, y = y)) +
geom_abline(
intercept = b0,
slope = b1,
color = col1,
size = line_size
) +
geom_point(alpha = .5) +
# labs(title = "Quantitative variable") +
scale_x_continuous(limits = c(0, 1)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_qual_2 <- df2 %>%
mutate(x = 1/2 * x + 1/4) %>%
ggplot(aes(x = x, y = y)) +
# geom_abline(
# intercept = b0,
# slope = b2,
# color = col1
# ) +
geom_point(
# data = tibble(x = c(0, 1), y = c(b0, b0 + b2)),
data = tibble(x = c(1/4, 3/4), y = c(b0, b0 + b2)),
mapping = aes(x = x, y = y),
color = col1,
size = 5#,
# alpha = .8
) +
geom_point(alpha = .5) +
geom_point(
# data = tibble(x = c(0, 1), y = c(b0, b0 + b2)),
data = tibble(x = c(1/4, 3/4), y = c(b0, b0 + b2)),
mapping = aes(x = x, y = y),
color = col1,
size = 5,
alpha = .8
) +
# labs(title = "Qualitative variable") +
scale_x_continuous(limits = c(0, 1)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_qual_3 <- df3 %>%
mutate(x2 = factor(x2)) %>%
ggplot(aes(x = x1, color = x2, y = y)) +
geom_abline(
intercept = b0,
slope = b1,
color = col1,
size = line_size
) +
geom_abline(
intercept = b0 + b2,
slope = b1,
color = col2,
size = line_size
) +
geom_point(alpha = .5) +
scale_color_manual(values = c(col1, col2)) +
# labs(title = "Quantitative and qualitative variable without interaction") +
scale_x_continuous(limits = c(0, 1)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_qual_4 <- df4 %>%
mutate(x2 = factor(x2)) %>%
ggplot(aes(x = x1, color = x2, y = y)) +
geom_abline(
intercept = b0,
slope = b1,
color = col1,
size = line_size
) +
geom_abline(
intercept = b0 + b2,
slope = b1 + b12,
color = col2,
size = line_size
) +
geom_point(alpha = .5) +
scale_color_manual(values = c(col1, col2)) +
# labs(title = "Quantitative and qualitative variable with interaction") +
scale_x_continuous(limits = c(0, 1)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
```
```{r, plot-quant-qual-print, out.width = "50%", fig.width = 5, fig.height = 3.5, fig.align='center', fig.cap=ifelse(knitr::is_html_output(), "(ref:expl-var-types-caption-gitbook)", "(ref:expl-var-types-caption-latex)"), label="expl-var-types", echo=FALSE, fig.ncol=2, fig.subcap=c('Quantitative', 'Qualitative', 'Quantitative and qualitative \\\\ without interaction', 'Quantitative and qualitative \\\\ with interaction'), cache = TRUE}
# To align the plots in a subfigure environment
plot_grid_split <- function(..., align = "hv", axis = "tblr"){
aligned_plots <- cowplot::align_plots(..., align = align, axis = axis)
plots <- lapply(1:length(aligned_plots), function(x){
cowplot::ggdraw(aligned_plots[[x]])
})
invisible(capture.output(plots))
}
plot_grid_split(p_quant_qual_1, p_quant_qual_2, p_quant_qual_3, p_quant_qual_4)
```
In the top-left panel, we see the effect of the quantitative variable $x$ in the model $\mu_i = \beta_0 + \beta_1 x_i$. As we can see it is a straight line. The coefficient $\beta_1$ represents the slope of the line, thus $\beta_1>0$ means that $x$ and $Y$ are positively correlated, while $\beta_1<0$ means that $x$ and $Y$ are negatively correlated. For example, if $x$ is the power of the vehicle and $Y$ the yearly number of claims, $\beta_1>0$ means that the more powerful the vehicle is, the more claims the policyholder will experience on average.
In the top-right panel, we see the effect of a qualitative binary variable $x$ in the model $\mu_i = \beta_0 + \beta_1 x_i$. The variable is encoded with values $0$ and $1$, so $\beta_1$ represents the effect of the modality $x=1$. In general, for a qualitative variable with $K$ modalities we will have $K-1$ dummy variables $x'_1, \dots, x'_{K-1}$ and the model will be $\mu_i = \beta_0 + \beta_1 x'_{i1} + \beta_2 x'_{i2} + \dots + + \beta_{K-1} x'_{i, K-1}$. Thus, the $\beta_j$ coefficient represents the relative effect of the modality $j$ compared to the base level modality, that is the one not explicitly included in the dummy encoding. For example, if $x$ is the vehicle make, $Y$ the yearly number of claims, the base level for $x$ is 'Fiat' and the $j$^th^ modality is 'Ferrari', then $\beta_j>0$ means that Ferrari cars on average experience more claims that Fiat cars.
In general, in a multivariate model, the coefficient $\beta_j$ represents the effect of the variable $j$ given all the others. In the example of Fiat and Ferrari cars, if in the model there is also the variable 'vehicle power', the coefficient $\beta_j$ corresponding to the modality 'Ferrari' represents the how more risky a Ferrari car is compared to a Fiat car with the same power. If the explanatory variables are strongly correlated, it is important to be aware of this aspect. For example, Ferrari cars are usually more powerful that Fiat cars. So, it is possible that in general Ferrari cars are more risky than Fiat cars, but comparing a Ferrari car to a Fiat with the same power, the Ferrari could be less risky. This effect is called _Simpson's paradox_ [@blyth1972simpson].
In the bottom-left panel of figure \@ref(fig:expl-var-types), we see the effect of a quantitative variable $x_1$ and a qualitative binary variable $x_2$ together in the model $\mu_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2}$. As we can seen, the effects of $x_1$ variable in the two groups defined by $x_2$ variable are represented by two parallel straight lines. The first one is $\mu_i = \beta_0 + \beta_1 x_{i1}$ and the second is $\mu_i = \left(\beta_0 + \beta_2\right) + \beta_1 x_{i1}$. The coefficient $\beta_2$ represents the vertical distance between the two lines.
In the bottom-right panel, the interaction effect between $x_1$ and $x_2$ is included in the model. The model becomes $\mu_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \beta_3 x_{i1} x_{i2}$. That means that the effect of $x_1$ variables depends on the determination of the $x_2$ variable. In the group with $x_2=0$ the effect is represented by the line $\mu_i = \beta_0 + \beta_1 x_i$; the group with $x_2=1$ the effect is represented by the line $\mu_i = \left(\beta_0 + \beta_2\right) + \left(\beta_1 + \beta_3\right) x_{i1}$.
For quantitative variables, it is possible to consider also non linear effects in \ac{glm}s. Some examples are reported in figure \@ref(fig:expl-var-quant-effect).
(ref:expl-var-quant-effect-caption-latex) Explanatory quantitative variables effects.
(ref:expl-var-quant-effect-caption-gitbook) Explanatory quantitative variables effects, polynomial degree 2 (top-left), polynomial degree 4 (top-right), piece-wise linear (bottom-left) and piece-wise polynomial degree 2 (bottom-right).
```{r, plot-quant-effect-build, echo = FALSE, cache = TRUE}
set.seed(42)
## Colors defined in index.Rmd
# col1 <- hue_pal()(2)[1]
# col2 <- hue_pal()(2)[2]
line_size <- 2
n <- 200
b0 <- 1
b1 <- 2
b2 <- 1
b12 <- -1
sigma <- 0.05
f1 <- function(x){1.5 * (x - .3)^2 + .25}
f2 <- function(x){20*(x - .5)^4 + -4 * (x - .8)^2 - 2 * x + 2}
f3 <- function(x){
case_when(
x <= .25 ~ -2 * x + 1,
x <= .75 ~ -1/2 * x + 5/8,
TRUE ~ 1/4
)
}
f4 <- function(x){
case_when(
x <= .75 ~ 1.5 * (x - .75)^2 + .2,
TRUE ~ .2
)
}
df <- tibble(x = runif(n = n, min = 0, max = 1)) %>%
mutate(
mu1 = f1(x),
mu2 = f2(x),
mu3 = f3(x),
mu4 = f4(x)
)
df$y1 <- rnorm(n = n, mean = df$mu1, sd = sigma)
df$y2 <- rnorm(n = n, mean = df$mu2, sd = sigma)
df$y3 <- rnorm(n = n, mean = df$mu3, sd = sigma)
df$y4 <- rnorm(n = n, mean = df$mu4, sd = sigma)
p_quant_effect_1 <- df %>%
select(x, value = y1) %>%
ggplot() +
stat_function(
fun = f1,
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1),
ylim = c(NA, 1.05)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_effect_2 <- df %>%
select(x, value = y2) %>%
ggplot() +
stat_function(
fun = f2,
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1),
ylim = c(NA, 1.05)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_effect_3 <- df %>%
select(x, value = y3) %>%
ggplot() +
# geom_vline(data = tibble(xint = c(.25, .75)),
# aes(xintercept = xint),
# linetype = "dotted") +
geom_vline(xintercept = c(.25, .75),
linetype = "dotted") +
stat_function(
fun = f3,
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1),
ylim = c(NA, 1.05)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
p_quant_effect_4 <- df %>%
select(x, value = y4) %>%
ggplot() +
geom_vline(xintercept = .75,
linetype = "dotted") +
stat_function(
fun = f4,
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1),
ylim = c(NA, 1.05)) +
easy_remove_axes(
which = "both",
what = "text",
teach = FALSE
)
```
```{r, plot-quant-effect-print, out.width = "50%", fig.width = 5, fig.height = 3.5, fig.align='center', fig.cap=ifelse(knitr::is_html_output(), "(ref:expl-var-quant-effect-caption-gitbook)", "(ref:expl-var-quant-effect-caption-latex)"), label="expl-var-quant-effect", echo=FALSE, fig.ncol=2, fig.subcap=c('Polynomial degree 2', 'Polynomial degree 4', 'Piece-wise linear', 'Piece-wise polynomial degree 2'), cache = TRUE}
# # To align the plots in a subfigure environment
# plot_grid_split <- function(..., align = "hv", axis = "tblr"){
# aligned_plots <- cowplot::align_plots(..., align = align, axis = axis)
# plots <- lapply(1:length(aligned_plots), function(x){
# cowplot::ggdraw(aligned_plots[[x]])
# })
# invisible(capture.output(plots))
# }
plot_grid_split(p_quant_effect_1, p_quant_effect_2, p_quant_effect_3, p_quant_effect_4)
```
The basic way to achieve it is by adding polynomial terms to the linear predictor. For instance, if $x$ is a quantitative variable, it is possible to add to the model the term $x^2$, obtaining the model $\mu_i = \beta_0 + \beta_1 x_{i} + \beta_2 x_i^2$. An example of model with both $x$ and $x^2$ terms is represented in top-left panel of figure \@ref(fig:expl-var-quant-effect). Adding the quadratic term, the effect graph becomes a parabola.
With the same logic, it is possible to add more power terms. In general, if we want to model $x$ with a polynomial of degree $d$, we can consider the model $\mu_i = \beta_0 + \beta_1 x_{i} + \beta_2 x_{i}^2 + \dots + \beta_d x_{i}^d$. In top-right panel of figure \@ref(fig:expl-var-quant-effect) a 4^th^ degree polynomial effect is represented. We highlight that the model is still considered linear, as the attribute "Linear" in "General Linear Model" is referred to the relation between the parameters $\beta_j$ and the linear predictor $\eta_i$ that is still linear.
Another way to model non liner effects of explanatory variables is to separate the effects by pieces. In bottom-left panel of figure \@ref(fig:expl-var-quant-effect) a case in which the $x$ effect is separated in 3 pieces is represented. As in all the pieces the effect is linear, the graph of the variable effect is a broken line. This effect can be achieved by adding to the model the terms $(x-\nu)_+$, where $(x)_+$ represents the positive part of $x$ ($(x)_+ = \max(0,x)$) and $\nu$ is the value of $x$ in the angular point. The $\nu$ values are called _knots_, If the knots are $\nu_1, \nu_2, \dots, \nu_m$, the model can be represented as $\mu_i = \beta_0 + \beta_1 x_i + \beta_2 (x_i-\nu_1)_+ + \beta_3 (x_i-\nu_2)_+ + \dots + \beta_{m+1} (x_i-\nu_m)_+$. This kind of functions are called _linear splines_ and will be further discussed in section \@ref(chap:gam). If we want the effect to be null from a certain point $\nu$, we can consider the variable $x' = \min(\nu, x)$ instead of $x$. This corresponds to aggregate to $\nu$ all the $x$ after $\nu$.
The piece-wise approach can be enhanced by also considering polynomial terms. For instance, in bottom-left panel of figure \@ref(fig:expl-var-quant-effect), the model represented is $\mu_i = \beta_0 + \left( x_i - \nu \right)_-^2$, where $(x)_-$ is the negative part of $x$ ($(x)_- = \min(0,x)$). $f(x) = (x-\nu)^2$ is a parabola with vertex in $\nu$. The fact of not adding the linear term leads to a monotonic effect made by a semi-parabola and a horizontal semi-line that starts from its vertex.
The examples represented in figures \@ref(fig:expl-var-types) and \@ref(fig:expl-var-quant-effect) are based on simulated data. That means that the linear predictor structure is known and the coefficients $\beta_0, \beta_1, \dots, \beta_J$ are known. In practice, the real model is not known and the coefficients and the structure must be estimated by the data. Thus, we can take assumptions on the structure and we can estimate the coefficients with $\hat{\beta}_0, \hat{\beta}_1, \dots, \hat{\beta}_J$. In many cases it is not so clear whether to consider or not a variable and how to consider it. For example, with the same data both bottom-left and bottom-right models could work fine. In section \@ref(chap:variable-selection) we are going to discuss some variables selection techniques for \ac{glm}.
<!--
* Qualitative variables / binary variables
+ Dummy variables
* Quantitative variables
+ Linear effects
+ Polynomial effects
- GAM reference
+ piece wise
* Interactions
+ Manual interactions
Problem: Scalability. Con p parametri ho choose(p, 2) possibili interazioni
-->
<!--
Disclaimer:
Non è nota a priori la forma del predittore lineare e va stimata
Nei grafici ho sempre rappresentato la curva coi veri \beta tramite i quali i punti sono stati simulati
Nella pratica i \beta non sono noti e avremo solo gli \hat{\beta}
-->
#### Link functions and relativities
As we mentioned in \@ref(chap:linear-exp-families), \ac{glm} supports several families. In figure \@ref(fig:resp-var) the models $g(\mu_i) = \beta_0 + \beta_1 x_i$ with different response variable distributions and link functions are represented.
In all the distribution we used the canonical link function, except for the Gamma, in which we adopted the function $g(\mu)=\log(\mu)$ instead of its canonical link function $g(\mu)=-\frac{1}{\mu}$.
In the Binomial case the canonical function is $g(p) = \log{\left(\frac{p}{1-p}\right)}$, that is called logit function. Its inverse is $g^{-1}(\eta) = \frac{e^{\eta}}{1 + e^{\eta}}$ and it is called logistic.
As we can see from the plots, a linear effect on $x$ corresponds to a logistic effect when the link is logit and to an exponential effect when the link is log.
(ref:resp-var-caption-latex) Response variables and link functions.
(ref:resp-var-caption-gitbook) Response variables and link functions, Normal - identity (top-left), Binomial - logit (top-right), Poisson - log (bottom-left) and Gamma - log (bottom-right).
```{r, plot-resp-var, echo = FALSE, cache = TRUE}
set.seed(42)
## Colors defined in index.Rmd
# col1 <- hue_pal()(2)[1]
# col2 <- hue_pal()(2)[2]
line_size <- 2
n <- 200
b0 <- -2
b1 <- 4
# b2 <- 1
# b12 <- -1
sigma <- .2
alpha <- 4
df <- tibble(x = runif(n = n, min = 0, max = 1)) %>%
mutate(
eta = b0 + b1 * x,
mu1 = eta,
mu2 = plogis(eta),
mu3 = exp(eta),
mu4 = exp(eta)
)
df$y1 <- rnorm(n = n, mean = df$mu1, sd = sigma)
df$y2 <- rbinom(n = n, size = 1, prob = df$mu2)
df$y3 <- rpois(n = n, lambda = df$mu3)
df$y4 <- rgamma(n = n, shape = alpha, rate = alpha/df$mu4)
p_resp_1 <- df %>%
select(x, value = y1) %>%
ggplot() +
geom_abline(
intercept = b0,
slope = b1,
col = col1,
size = line_size
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1)) +
easy_remove_axes(
which = "x",
what = "text",
teach = FALSE
) +
labs(x = "x", y = "y")
p_resp_2 <- df %>%
select(x, value = y2) %>%
ggplot() +
stat_function(
fun = function(x){plogis(b0 + b1 * x)},
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 1)) +
easy_remove_axes(
which = "x",
what = "text",
teach = FALSE
) +
labs(x = "x", y = "y")
p_resp_3 <- df %>%
select(x, value = y3) %>%
ggplot() +
stat_function(
fun = function(x){exp(b0 + b1 * x)},
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10, 12),
minor_breaks = 0:12) +
coord_cartesian(xlim = c(0, 1),
ylim = c(0, 11)) +
easy_remove_axes(
which = "x",
what = "text",
teach = FALSE
) +
labs(x = "x", y = "y")
p_resp_4 <- df %>%
select(x, value = y4) %>%
ggplot() +
stat_function(
fun = function(x){exp(b0 + b1 * x)},
col = col1,
size = line_size,
xlim = c(-0.05, 1.05)
) +
geom_point(aes(x = x, y = value),
alpha = .4) +
# scale_x_continuous(limits = c(0, 1)) +
scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10, 12),
minor_breaks = 0:12) +
coord_cartesian(xlim = c(0, 1),
ylim = c(0, 11)) +
easy_remove_axes(
which = "x",
what = "text",
teach = FALSE
) +
labs(x = "x", y = "y")
```
```{r, plot-quant-effect-print, out.width = "50%", fig.width = 5, fig.height = 3.5, fig.align='center', fig.cap=ifelse(knitr::is_html_output(), "(ref:resp-var-caption-gitbook)", "(ref:resp-var-caption-latex)"), label="resp-var", echo=FALSE, fig.ncol=2, fig.subcap=c('Normal - identity', 'Binomial - logit', 'Poisson - log', 'Gamma - log'), cache = TRUE}
# # To align the plots in a subfigure environment
# plot_grid_split <- function(..., align = "hv", axis = "tblr"){
# aligned_plots <- cowplot::align_plots(..., align = align, axis = axis)
# plots <- lapply(1:length(aligned_plots), function(x){
# cowplot::ggdraw(aligned_plots[[x]])
# })
# invisible(capture.output(plots))
# }
plot_grid_split(p_resp_1, p_resp_2, p_resp_3, p_resp_4,
align = "h")
```
If $g(\mu) = \log(\mu)$, the model structure can be expressed as:
\begin{align*}
\mu_i & = e^{\beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \dots + \beta_p x_{ip}} \\
& = e^{\beta_0} \left(e^{\beta_1}\right)^{x_{i1}} \left(e^{\beta_2}\right)^{x_{i2}} \dots \left(e^{\beta_p}\right)^{x_{ip}}
\end{align*}
The term $e^{\beta_j}$ can be seen as the multiplicative factor corresponding to the variable $x_j$. If $x_j$ is a dummy variable, $e^{\beta_j}$ is the factor the expected value $\mu_i$ is multiplied by when $x_{ij}=1$. If $x_j$ is a quantitative variable, $e^{\beta_j}$ is the factor the expected value $\mu_i$ is multiplied by for every one-unit increasing of $x_{ij}$. Indeed:
$$\left(e^{\beta_j}\right)^{x_j+1} = e^{\beta_j} \left(e^{\beta_j}\right)^{x_j}$$
The fact that with a log link the relation between coefficients $\beta_0, \beta_1, \dots, \beta_p$ and expected value $\mu_i$ becomes multiplicative is particularly useful to deal with exposure $v_i$. In section \@ref(chap:exposure) we have seen that often the observations are couples (policy, accounting year), so they have different exposures $v_i$. Thus, we usually work with the number of claims occurred in the exposure period $M_i$ and we observe its realization $m_i$. The assumption we take is that:
$$M_i \sim Poisson(v_i \mu_i)$$
where $\mu_i$ is the expected value of the yearly number of claims $N_i$.
Under the \ac{glm} assumptions, we obtain
\begin{align*}
E(M_i) & = v_i \mu_i = v_i e^{\beta_0 + \beta_1 x_{i1} + \dots + \beta_p x_{ip}} \\
& = e^{\log(v_i)}e^{\beta_0 + \beta_1 x_{i1} + \dots + \beta_p x_{ip}} \\
& = e^{\beta_0 + \beta_1 x_{i1} + \dots + \beta_p x_{ip} + \log(v_i)}
\end{align*}
That means that we can model $M_1, M_2, \dots, M_n$ as response variables in a \ac{glm} with Poisson response in which the linear predictor depends on an offset additive term $\log(v_i)$.
If $g(p) = \text{logit}(p)$, the model structure can be expressed as:
\begin{align*}
\frac{p_i}{1-p_i} & = e^{\beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \dots + \beta_p x_{ip}} \\
& = e^{\beta_0} \left(e^{\beta_1}\right)^{x_{i1}} \left(e^{\beta_2}\right)^{x_{i2}} \dots \left(e^{\beta_p}\right)^{x_{ip}}
\end{align*}
Thus, the term $e^{\beta_j}$ can be seen as the multiplicative relativity corresponding to the variable $x_j$. However, in this case the relativity doesn't multiply directly the probability of success $p$, but it multiplies the odds of success $\frac{p}{1-p}$.
#### Variables selection {#chap:variable-selection}
One of the most challenging aspects of \ac{glm} fitting is selecting the variables and their effects by looking to observed data. In practice, we usually have many explanatory variables available but only some of them are relevant for the prediction of the response variable. Adding useless variables to the model increases the variance of the estimators of the coefficients $\tilde{\beta}_0, \tilde{\beta}_1, \dots, \tilde{\beta}_p$ and then the variance of the predictions $\tilde{\mu}_i = \tilde{\beta}_0 + \tilde{\beta}_1 x_{i1} + \dots + \tilde{\beta}_p x_{ip}$. On the other hand, being too frugal with explanatory variables could lead to wasting part of the predictive power of the available explanatory variables.
One useful tool that can help us understand if an explanatory variable $x$ is relevant or not is plotting the points $(x_i, y_i)$, as we did in figures \@ref(fig:expl-var-types), \@ref(fig:expl-var-quant-effect) and \@ref(fig:resp-var). If there are too many observations and the plot is not easily readable, it is possible to group the points by $x$ modalities and show for each group the average of $y_i$ and a confidence interval that gives an idea on the dispersion of the observations around the average. If $x$ is a continuous variable with too many modalities, it is possible to group them into buckets. Showing the average of $y_i$ for groups of $x$ is particularly useful for Binomial and Poisson data, where the fact that $y_i$ can present few different values compromises the plot readability. An example is reported in figure \@ref(fig:var-selection). The top-left and bottom-left panels represent a case in which $x$ and $y$ are not related, while the top-right and bottom-right panels represent a case of positive correlation. From the ungrouped plot in the top-right panel the effect is not clear, while from bottom-right panel it is evident.
(ref:var-selection-caption-latex) Explanatory variable effect evaluation. The top-left and bottom-left panels represent a case in which $x$ and $y$ are not related, while the top-right and bottom-right panels represent a case of positive correlation. From the ungrouped plot in the top-right panel the effect is not clear, while from bottom-right panel it is evident.
(ref:var-selection-caption-gitbook) Explanatory variable effect evaluation, No effect - ungrouped (top-left), Positive effect - ungrouped (top-right), No effect - grouped (bottom-left) and Positive effect - grouped (bottom-right). The top-left and bottom-left panels represent a case in which $x$ and $y$ are not related, while the top-right and bottom-right panels represent a case of positive correlation. From the ungrouped plot in the top-right panel the effect is not clear, while from bottom-right panel it is evident.
(ref:var-selection-caption-short) Explanatory variable effect evaluation.
```{r, plot-var-selection, message=FALSE, out.width = "50%", fig.align='center', fig.cap=ifelse(knitr::is_html_output(), "(ref:var-selection-caption-gitbook)", "(ref:var-selection-caption-latex)"), fig.scap="(ref:var-selection-caption-short)", label="var-selection", echo=FALSE, fig.ncol=2, fig.subcap=c('No effect - ungrouped', 'Positive effect - ungrouped', 'No effect - grouped', 'Positive effect - grouped'), cache = TRUE}
set.seed(42)
## Colors defined in index.Rmd
# col1 <- hue_pal()(2)[1]
# col2 <- hue_pal()(2)[2]
line_size <- 2
n <- 1000
b0 <- -2
b1 <- 4
sigma <- 2
df <- tibble(x = rbeta(n = n, shape1 = 3, shape2 = 3)) %>%
mutate(
mu1 = 0,
mu2 = b0 + b1 * x,
x_group = floor(10*x) / 10 + 0.05
)
df$y1 <- rnorm(n = n, mean = df$mu1, sd = sigma)
df$y2 <- rnorm(n = n, mean = df$mu2, sd = sigma)
# Top-left plot
p_var_selection_1 <- df %>%
select(x, value = y1) %>%
ggplot() +
geom_point(aes(x = x, y = value),
alpha = .4) +
coord_cartesian(xlim = c(0, 1),
ylim = c(-7, 7)) +
labs(x = "x", y = "y")
p_var_selection_1
# Top-right plot
p_var_selection_2 <- df %>%
select(x, value = y2) %>%
ggplot() +
geom_point(aes(x = x, y = value),
alpha = .4) +
coord_cartesian(xlim = c(0, 1),
ylim = c(-7, 7)) +
labs(x = "x", y = "y")
p_var_selection_2
# Aggregate data
df_summary <- df %>%
group_by(x_group) %>%
summarize(
n = n(),
y1_mean = mean(y1),
y1_sd = sd(y1) / sqrt(n),
y2_mean = mean(y2),
y2_sd = sd(y2) / sqrt(n)
) %>%
mutate(
y1_up = y1_mean + 2 * y1_sd,
y1_down = y1_mean - 2 * y1_sd,
y2_up = y2_mean + 2 * y2_sd,
y2_down = y2_mean - 2 * y2_sd
)
# Bottom-left plot
df_plot_1 <- df_summary %>%
select(x = x_group, mean = y1_mean, down = y1_down, up = y1_up, n) %>%
pivot_longer(cols = c("mean", "n"),
names_to = "variable", values_to = "value") %>%
mutate(variable = factor(variable, levels = c("mean", "n")))
p_1 <- df_plot_1 %>%
mutate(x = factor(x)) %>%
ggplot(aes(x = x, y = value)) +
facet_grid(
variable ~ .,
scales = "free",
labeller = labeller(variable = c("mean" = "y", "n" = "count"))
) +
geom_point(data = filter(df_plot_1, variable == "mean")) +
geom_line(data = filter(df_plot_1, variable == "mean"),
group = 1) +