Learning Parameters

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.

Show The Code
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'
Show The Code
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)

Show The Code
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)
Show The Code
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')

Show The Code
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()
name Average Value
Coefficient 0.94
Intercept -0.44

We learned that on average when the predictor is 0, there is a -0.44 log of the odds or 0.64 odds or 0.39 probability to be in the outcome group (Y=1).

On average, there is a 0.94 expected change in the log of the odds or 2.56 odds for a one-unit increase in the predictor. In other words, we expect to see a 72% increase in the odds of being in the outcome group (Y=1) as the predictor increases by one-unit.

Show The Code
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())

Show The Code
anim_save("mccv_parameters_animation.gif")

On the other hand, MCCV is unable to learn stable parameter values when the data is shuffled:

Show The Code
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)
Show The Code
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')

Show The Code
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()
name Average Value
Coefficient -0.02
Intercept 0.01
Show The Code
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())

Show The Code
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).