-
Notifications
You must be signed in to change notification settings - Fork 0
/
mccv_parameters.qmd
205 lines (171 loc) · 6.57 KB
/
mccv_parameters.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
---
title: "Learning Parameters"
format:
html:
code-fold: true
code-summary: 'Show The Code'
---
Refitting the model per learned parameters from K-fold cross validation during training is a key step in the Monte Carlo Cross Validation (MCCV) methodology. However, the `run_mccv()` function that runs the entire MCCV procedure does not return these learned parameters. In this article, the learned parameters are extracted from 10-fold cross validation of a Logistic Regression model. These learned parameters are 200 intercepts and coefficients later refit to the entire training set. Here, we visualize the distribution of the learned parameters to illustrate the learning process.
```{python}
#| warning: false
#| cache: true
import numpy as np
import scipy as sc
import pandas as pd
N=100
np.random.seed(0)
Z1 = np.random.beta(2,3,size=N,)
np.random.seed(0)
Z2 = np.random.beta(2,2.5,size=N)
Z = np.concatenate([Z1,Z2])
Y = np.concatenate([np.repeat(0,N),np.repeat(1,N)])
df = pd.DataFrame(data={'Y' : Y,'Z' : Z})
df.index.name = 'pt'
```
```{r}
#| warning: false
library(tidyverse)
df <- tibble::tibble(
Y = reticulate::py$Y,
Z = reticulate::py$Z
)
df[['Y']] <- factor(df$Y,levels=c(0,1))
df %>%
ggplot(aes(Y,Z)) +
geom_boxplot(outlier.size = NA,alpha=0,linewidth=2) +
geom_point(position = position_jitter(width = .2),pch=21,fill='gray',size=3) +
labs(x = "Response",y="Predictor") +
theme_bw(base_size = 16)
```
```{python}
#| cache: true
import mccv
import pandas as pd
mccv_obj = mccv.mccv(num_bootstraps=200,n_jobs=4)
mccv_obj.set_X(df[['Z']])
mccv_obj.set_Y(df[['Y']])
param_dfs=[]
for seed in range(200):
retrained_fit = mccv_obj.mccv(seed)[1]['Logistic Regression'].__dict__
param_dict = {k : retrained_fit[k].reshape(-1)[0] for k in ('coef_','intercept_')}
param_df = pd.DataFrame.from_dict(param_dict,orient='index',dtype='object',columns=[seed])
param_dfs.append(param_df)
retrained_parameters_df = pd.concat(param_dfs,axis=1).T
retrained_parameters_df.index.name='seed'
retrained_parameters_df.reset_index(inplace=True)
```
```{r}
library(tidyverse)
plot_dat <-
reticulate::py$retrained_parameters_df %>%
pivot_longer(
cols = contains('_')
) %>%
mutate(
seed = as.integer(seed),
name = factor(name,levels=c("intercept_","coef_"),labels=c("Intercept","Coefficient")),
value = as.double(value)
)
p <-
plot_dat %>%
ggplot(aes(name,value,group=seed)) +
geom_line() +
scale_x_discrete(
expand = expansion(0.01,0.01),
name=NULL
) +
scale_y_continuous(
name="Parameter Values"
) +
labs(caption='Estimated Parameters From 200 Logistic Regression Bootstraps') +
theme_bw(base_size = 20) +
theme(
axis.text.x = element_text(angle=45,hjust=1,vjust=1)
)
p +
stat_summary(fun=mean,color='red',geom='line',aes(group=1),linewidth=3) +
labs(caption='Estimated Parameters From 200 Logistic Regression Bootstraps\nAverage in Red')
avg_values <-
summarise(plot_dat,`Average Value` = mean(value),.by=name) %>%
mutate(across(where(is.numeric),function(x)round(x,2)))
avg_values %>%
gt::gt()
```
We learned that on average when the predictor is 0, there is a `r intercept_ = dplyr::pull(dplyr::filter(avg_values,name=="Intercept"),"Average Value")` `r round(intercept_,2)` log of the odds or `r round(exp(intercept_),2)` odds or `r round(exp(intercept_)/(1+exp(intercept_)),2)` probability to be in the outcome group (Y=1).
On average, there is a `r coef_ = dplyr::pull(dplyr::filter(avg_values,name=="Coefficient"),"Average Value")` `r round(coef_,2)` expected change in the log of the odds or `r round(exp(coef_),2)` odds for a one-unit increase in the predictor. In other words, we expect to see a `r paste0(round(exp(coef_)/(1+exp(coef_)),2)*100,"%")` increase in the odds of being in the outcome group (Y=1) as the predictor increases by one-unit.
```{r}
library(gganimate)
#install.packages("transformr")
animp <-
p +
transition_time(seed) +
labs(title="Seed : {frame_time}")
animate(animp,duration = 5, fps = 20, width = 500, height = 500, renderer = gifski_renderer())
anim_save("mccv_parameters_animation.gif")
```
On the other hand, MCCV is unable to learn stable parameter values when the data is shuffled:
```{python}
#| cache: true
import mccv
import pandas as pd
mccv_obj = mccv.mccv(num_bootstraps=200,n_jobs=4)
mccv_obj.set_X(df[['Z']])
mccv_obj.set_Y(df[['Y']])
param_dfs=[]
for seed in range(200):
retrained_fit = mccv_obj.permuted_mccv(seed)[1]['Logistic Regression'].__dict__
param_dict = {k : retrained_fit[k].reshape(-1)[0] for k in ('coef_','intercept_')}
param_df = pd.DataFrame.from_dict(param_dict,orient='index',dtype='object',columns=[seed])
param_dfs.append(param_df)
retrained_parameters_df = pd.concat(param_dfs,axis=1).T
retrained_parameters_df.index.name='seed'
retrained_parameters_df.reset_index(inplace=True)
```
```{r}
library(tidyverse)
plot_dat <-
reticulate::py$retrained_parameters_df %>%
pivot_longer(
cols = contains('_')
) %>%
mutate(
seed = as.integer(seed),
name = factor(name,levels=c("intercept_","coef_"),labels=c("Intercept","Coefficient")),
value = as.double(value)
)
p <-
plot_dat %>%
ggplot(aes(name,value,group=seed)) +
geom_line() +
scale_x_discrete(
expand = expansion(0.01,0.01),
name=NULL
) +
scale_y_continuous(
name="Parameter Values"
) +
labs(caption='Permuted MCCV\nEstimated Parameters From 200 Logistic Regression Bootstraps') +
theme_bw(base_size = 20) +
theme(
axis.text.x = element_text(angle=45,hjust=1,vjust=1)
)
p +
stat_summary(fun=mean,color='red',geom='line',aes(group=1),linewidth=3) +
labs(caption='Permuted MCCV\nEstimated Parameters From 200 Logistic Regression Bootstraps\nAverage in Red')
avg_values <-
summarise(plot_dat,`Average Value` = mean(value),.by=name) %>%
mutate(across(where(is.numeric),function(x)round(x,2)))
avg_values %>%
gt::gt()
```
```{r}
library(gganimate)
#install.packages("transformr")
animp <-
p +
transition_time(seed) +
labs(title="Seed : {frame_time}")
animate(animp,duration = 5, fps = 20, width = 500, height = 500, renderer = gifski_renderer())
anim_save("permuted_mccv_parameters_animation.gif")
```
The distribution of parameters from the permuted MCCV provides a null distribution. The alternative hypothesis is learned parameters from MCCV (using the real data) is different from parameters estimated from permuted MCCV (using shuffled data).