# Python Practice Lecture 16 MATH 342W Queens College - K-fold Cross Validation
## Author: Amir ElTabakh
## Date: April 5, 2022

## Agenda:
* The K Tradeoff
* Reducing variance with Cross Validation (i.e. K-fold CV)

## The K Tradeoff

$K$ determines how large the training set is relative to the test set when you're doing honest validation for an algorithm. For now, let's not use K-fold CV, but only examine one split at a time. Consider this simulated dataset with 50 observations:


```python
# importing dependencies
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error # calculates RMSE
import pandas as pd
import random

# ignore warnings
import warnings
warnings.filterwarnings("ignore")

# Data viz
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_palette(sns.color_palette("colorblind")) # setting color palette
sns.set(rc={"figure.figsize":(10, 6)}) #width=10, #height=6
```


```python
# setting seed
np.random.seed(2022)

# constants
n = 50
xmin = 0
xmax = 4

# data vecs
x = np.random.uniform(low = xmin, high = xmax, size = n)
y = [2 + 3 * i ** 2 + np.random.normal(0, 0.8) for i in x]

# convert to df
Xy = pd.DataFrame({'y': y, 'x': x})

# snapshot
Xy.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>y</th>
      <th>x</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1.475622</td>
      <td>0.037434</td>
    </tr>
    <tr>
      <th>1</th>
      <td>13.308573</td>
      <td>1.996231</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3.327321</td>
      <td>0.453535</td>
    </tr>
    <tr>
      <th>3</th>
      <td>1.945917</td>
      <td>0.199896</td>
    </tr>
    <tr>
      <th>4</th>
      <td>23.797992</td>
      <td>2.741630</td>
    </tr>
  </tbody>
</table>
</div>




```python
from plotnine import ggplot, aes, geom_point

# plot the data
data_plot = ggplot(Xy) + aes(x = x, y = y) + geom_point()
data_plot
```

Note how $f(x)$ is quadratic and there is random noise which is "ignorance error". The random noise will be part of generalization error and can never go away.

If we use OLS with no derived features, then we can at most get $h*(x)$. Let's see what $h^*(x) = \beta_0 + \beta_1 x$ truly is. To do this, we imagine we see an absolute ton of data and run OLS on it.


```python
# setting seed
np.random.seed(1738)

n_hidden = 1e6

# data vecs
x_hidden = np.random.uniform(low = xmin, high = xmax, size = n)
y_hidden = [2 + 3 * i ** 2 + np.random.normal(0, 0.8) for i in x_hidden]

# convert to dataframes
x_hidden = pd.DataFrame(x_hidden)
y_hidden = pd.DataFrame(y_hidden)


# h_*
h_star_model = LinearRegression().fit(x_hidden, y_hidden)

print(h_star_model.intercept_[0], h_star_model.coef_[0][0])
```

    -5.7301681875688715 11.925324444538758


The fact that $\beta = [-6~12]^\top$ can actually be solved with calculus: $\int_0^4 ((2 + 3x^2) - (b_0 + b_1 x))^2 dx$ and solve for $b_0$ and $b_1$ explicitly by minimizing.

Plotting that over $\mathbb{D}$ we obtain


```python
from plotnine import geom_abline

data_plot + geom_abline(
    intercept = h_star_model.intercept_[0],
    slope = h_star_model.coef_[0][0],
    color = 'green')
```

That is the best we're going to get. However, $g_{final}$ falls far short of it:


```python
# h_*
g_final_model = LinearRegression().fit(Xy[['x']], Xy[['y']])

print(g_final_model.intercept_[0], g_final_model.coef_[0][0])
```

    -5.779880916597136 12.040200380319078


The actual standard error of g_final can be estimated by imagining tons of future observations:


```python
y_hat_g_final = g_final_model.predict(x_hidden)

gen_error_true = np.std(y_hidden - y_hat_g_final)
gen_error_true[0]
```




    3.895685515342658



The model $g$ can vary quite a bit as we subsample $\mathbb{D}$ which is what happens when you do train-test splits. It varies a lot because there is large misspecification error. If the model was correctly specified, the results of everything that follows will be less impressive. But in the real world - is your model ever correctly specified? is $f \in \mathcal{H}$?? NO. So this is more realistic.

Now let's let K be small. Let K = 2 meaning even 50-50 split of test and train.

Sets, initialized with paranthesis, not square brackets, allow us to reduce one list from the other using the subtract operator.


```python
# setting seed
random.seed(17388) # two different libraries to set seeds for

# constants
K = 2
prop_train = (K - 1) / K
n_train = int(prop_train * n)

# train test split indices
indices = set([i for i in range(n)])
index_train = set(random.sample(indices, n_train))
index_test = indices - index_train

# split based on indices
x_train = pd.DataFrame([x[i] for i in index_train]) # cast from set to list
y_train = pd.DataFrame([y[i] for i in index_train])

x_test = pd.DataFrame([x[i] for i in index_test])
y_test = pd.DataFrame([y[i] for i in index_test])

# fitting model
g_mod = LinearRegression().fit(x_train, y_train)

# yhat via test set
y_hat_g_test = g_mod.predict(x_test)

# yhat via train set
y_hat_g_train = g_mod.predict(x_train)

# standard error
gen_error_K_2_test = np.std(y_test - y_hat_g_test) # test
gen_error_K_2_train = np.std(y_train - y_hat_g_train) # train

print(gen_error_true[0]) # true standard error
print(gen_error_K_2_test[0]) # tested standard error
```

    3.895685515342658
    3.866651151341103


Although I cooked the books by setting the seed, this realization makes sense. If K=2, I build the model g with half the data than the model g_final. Less data to train on => higher generalization error. How about if K is large. Let's say $K = \frac{n}{2}$ meaning $n_{train} = 48$ and $n_{test} = 2$.


```python
# setting seed
np.random.seed(7777)
random.seed(7777) # two different libraries to set seeds for

# constants
K = n / 2
prop_train = (K - 1) / K
n_train = int(prop_train * n)

# train test split indices
indices = set([i for i in range(n)])
index_train = set(random.sample(indices, n_train))
index_test = indices - index_train

# split based on indices
x_train = pd.DataFrame([x[i] for i in index_train]) # cast from set to list
y_train = pd.DataFrame([y[i] for i in index_train])

x_test = pd.DataFrame([x[i] for i in index_test])
y_test = pd.DataFrame([y[i] for i in index_test])

# fitting model
g_mod = LinearRegression().fit(x_train, y_train)

# yhat via test set
y_hat_g_test = g_mod.predict(x_test)

# yhat via train set
y_hat_g_train = g_mod.predict(x_train)

# standard error
gen_error_K_2_test = np.std(y_test - y_hat_g_test) # test
gen_error_K_2_train = np.std(y_train - y_hat_g_train) # train

print(gen_error_true[0]) # true standard error
print(gen_error_K_2_test[0]) # tested standard error
print(gen_error_K_2_train[0]) # train standard error
```

    3.895685515342658
    4.721271620787243
    3.9750058046527084


Although I cooked the books again by setting the seed, this also makes sense. More data to train on means less error but still more error than all the data. In reality, there is massive variance over specific splits! Let's run the simulation with these two K values many times.

While we're at it, let's do all K's! Well, what are all the valid K's? If you want to keep the sizes the same, any factorization of n except the trivial 1 since n = 1 * n. A $K = 1$ would mean there's no split! How to find divisors? Of course a package for this.


```python
# import divisors() method from sympy
from sympy import divisors

Kuniques = list(set(divisors(n)) - set([1]))
Kuniques
```




    [2, 5, 10, 50, 25]



But should we also include the trivial n? Yes K = n is indeed a valid divisor. And this type of CV is called the "leave one out cross validation" (LOOCV). Now we compute the errors over K:


```python
# constants
Nsim_per_K = 2000 # simulations per K fold
num_Kuniques = len(Kuniques)
Ks = Kuniques * Nsim_per_K

results = pd.DataFrame({'standard_error': [0 for i in range(Nsim_per_K * num_Kuniques)],
                        'K': [0 for i in range(Nsim_per_K * num_Kuniques)]})

for i in range(len(Ks)):
    # constants
    K = Ks[i]
    prop_train = (K - 1) / K
    n_train = int(prop_train * n)

    # train test split indices
    indices = set([i for i in range(n)])
    index_train = set(random.sample(indices, n_train))
    index_test = indices - index_train

    # split based on indices
    X_train = pd.DataFrame([x[i] for i in index_train]) # cast from set to list
    y_train = pd.DataFrame([y[i] for i in index_train])

    X_test = pd.DataFrame([x[i] for i in index_test])
    y_test = pd.DataFrame([y[i] for i in index_test])

    # fitting model
    g_mod = LinearRegression().fit(X_train, y_train)
    
    # get predictions
    y_hat_g = g_mod.predict(X_test)
    
    # get error metric
    if len(y_test) == 1:
        g_s_e = np.absolute([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    else:
        g_s_e = np.std([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    
    # update results
    results.loc[i] = np.asarray([g_s_e, K])
    
# output results
results
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>standard_error</th>
      <th>K</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>4.854482</td>
      <td>2.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2.285150</td>
      <td>5.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3.105590</td>
      <td>10.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>7.310184</td>
      <td>50.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>0.852891</td>
      <td>25.0</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>9995</th>
      <td>4.322564</td>
      <td>2.0</td>
    </tr>
    <tr>
      <th>9996</th>
      <td>2.757709</td>
      <td>5.0</td>
    </tr>
    <tr>
      <th>9997</th>
      <td>3.843814</td>
      <td>10.0</td>
    </tr>
    <tr>
      <th>9998</th>
      <td>3.889604</td>
      <td>50.0</td>
    </tr>
    <tr>
      <th>9999</th>
      <td>0.186950</td>
      <td>25.0</td>
    </tr>
  </tbody>
</table>
<p>10000 rows × 2 columns</p>
</div>



What are the variabilities? Let's take the average error over each simulated split. 


```python
# mean of the standard errors grouped by K
results_summary = pd.DataFrame({'K': list(results.groupby(['K']).mean().index),
                                 'K_avg': list(results.groupby(['K']).mean()['standard_error']),
                                 'K_SE': list(results.groupby(['K']).std()['standard_error'])
                                }).set_index('K')

results_summary
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>K_avg</th>
      <th>K_SE</th>
    </tr>
    <tr>
      <th>K</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2.0</th>
      <td>4.138852</td>
      <td>0.349815</td>
    </tr>
    <tr>
      <th>5.0</th>
      <td>3.923679</td>
      <td>0.598949</td>
    </tr>
    <tr>
      <th>10.0</th>
      <td>3.586957</td>
      <td>0.995828</td>
    </tr>
    <tr>
      <th>25.0</th>
      <td>2.351176</td>
      <td>1.800594</td>
    </tr>
    <tr>
      <th>50.0</th>
      <td>3.716647</td>
      <td>1.875211</td>
    </tr>
  </tbody>
</table>
</div>




```python
sns.displot(results,
             x = 'standard_error',
             hue = 'K',
             kind = 'kde',
             multiple="stack",
             palette = 'bright',
             alpha = 0.9,
             aspect = 1.5) # width = height * aspect

plt.axvline(label='Mean 2.0', x=results_summary.iloc[0, 0], color='blue')
plt.axvline(label='Mean 5.0', x=results_summary.iloc[1, 0], color='orange')
plt.axvline(label='Mean 10.0', x=results_summary.iloc[2, 0], color='green')
plt.axvline(label='Mean 25.0', x=results_summary.iloc[3, 0], color='red')
plt.axvline(label='Mean 50.0', x=results_summary.iloc[4, 0], color='purple')
```

The main takeaways are

1. The std err of generalization error estimate is much lower for low K than high K

With high K, the test set is small meaning the estimate has high variance; with low K, the test set is large meaning you can measure it with low variance.

2. The average of generalization error estimate is lower for high K than low K

With high K, the training set is large meaning $g$ is closer to g_final and thus has higher expected accuracy; with low K, the training set is small meaning $g$ is further from g_final and thus has lower expected accuracy.

Thus, the tradeoff is bias vs. variance. There are many similar tradeoffs in statistics. We will see one later when we do machine learning.

Is the estimates' accuracy for what we really care about? No, the generalization error of g_final which we picture below:


```python
sns.displot(results,
             x = 'standard_error',
             hue = 'K',
             kind = 'kde',
             multiple="stack",
             palette = 'bright',
             alpha = 0.9,
             aspect = 1.5) # width = height * aspect

plt.axvline(label='Mean 2.0', x=results_summary.iloc[0, 0], color='blue')
plt.axvline(label='Mean 5.0', x=results_summary.iloc[1, 0], color='orange')
plt.axvline(label='Mean 10.0', x=results_summary.iloc[2, 0], color='green')
plt.axvline(label='Mean 25.0', x=results_summary.iloc[3, 0], color='red')
plt.axvline(label='Mean 50.0', x=results_summary.iloc[4, 0], color='purple')
plt.axvline(label='CV', x=gen_error_true[0], color='white')

```

Remember, g_final's error should be lower than both averages since it uses all the data. But we see above it's higher!

So what happened? Simple... we are mixing apples and oranges. We calculated that white line by looking at one million future observations. We calculated the red and blue distributions by looking at our data only which is a random realization of many such datasets! Thus, our generalization errors are biased based on the specific n observations in D we received. We will see that K-fold helps a bit with this. But there is nothing we can do about it beyond that (besides collect more observations). If you get a weird sample, you get a weird sample!

How would we be able to generate the picture we really want to see? We would run this simulation over many datasets and average. That would be a giant simulation. To show that this is the case, go back and change the seed in the first chunk and rerun. You'll see a different white bar.

What is the main takeaway? K matters because it induces a tradeoff. It shouldn't be too large or too small (as we believe at the moment). And, generalization error estimation is very variable in low n. To see this, go back and increase n.

## Reducing variance with Cross Validation (i.e. K-fold CV)

We saw previous there was a lot of variance in generalization error estimation. We can reduce some of this variance by using a very simple trick. We can rotate the train-test split so that each observation will be in the test set once. How many times is this done? K. Now we see the reason for the definition of K as it tells you how many times you validate. Why is it called "cross"? Because the training set crosses over as it does the rotation. Each observation is inside a training set K-1 times. This point will become important later. Why is it called K-fold? Because a fold is one set of training-test and there are K unique folds during the whole procedure.

How does this work? Well, let's say K=10, a typical value. This means in each "fold", 90% of the data is in the training set and 10% of the data is in the test set. As we run through the K folds, we train a model on the training set and predict on the test set and compute oos residuals We aggregate those oos residuals over the folds to result in n oos residuals. We then run our error metric on all n.

Let's begin with the dataset from the previous demo. Here is that code that will create the folds by specifying the K=10 test sets by index. The training sets can then be found by the set difference function.

We're gonna jump right into using sci-kit learn's KFold module. 


```python
# importing dependencies
from sklearn.model_selection import KFold

# initializing model
model = LinearRegression() # intercept will fit by default

# 10 folds
K = 10
kf = KFold(n_splits=K)

# list to hold residuals
oos_cross_validation_residuals = []

for train_index , test_index in kf.split(x):
    X_train = pd.DataFrame([x[i] for i in train_index])
    y_train = pd.DataFrame([y[i] for i in train_index])

    X_test = pd.DataFrame([x[i] for i in test_index])
    y_test = pd.DataFrame([y[i] for i in test_index])
    
    model.fit(X_train,y_train)
    y_hat_g = model.predict(X_test)
     
    oos_cross_validation_residuals += [np.std(y_test - y_hat_g)]
    
oos_cross_validation_residual_average = np.std(oos_cross_validation_residuals)
oos_cross_validation_residual_average
```




    0.8584252859259888



How does this CV error look over K? 


```python
# import divisors() method from sympy
from sympy import divisors

Kuniques = list(set(divisors(n)) - set([1]))
Kuniques
```




    [2, 5, 10, 50, 25]




```python
# constants
Nsim_per_K = 1 # simulations per K fold
num_Kuniques = len(Kuniques)
Ks = Kuniques * Nsim_per_K
n = len(y)

oos_residuals_CV = pd.DataFrame({'standard_error': [0 for i in range(Nsim_per_K * num_Kuniques)],
                        'K': [0 for i in range(Nsim_per_K * num_Kuniques)]})

for i in range(len(Ks)):
    # constants
    K = Ks[i]
    prop_train = (K - 1) / K
    n_train = int(prop_train * n)

    # train test split indices
    indices = set([i for i in range(n)])
    train_index = set(random.sample(indices, n_train))
    test_index = indices - train_index
    
    # cast as lists
    train_index = list(train_index)
    test_index = list(test_index)

    # split based on indices
    X_train = pd.DataFrame([x[i] for i in train_index])
    y_train = pd.DataFrame([y[i] for i in train_index])

    X_test = pd.DataFrame([x[i] for i in test_index])
    y_test = pd.DataFrame([y[i] for i in test_index])

    # fitting model
    g_mod = LinearRegression().fit(X_train, y_train)
    
    # get predictions
    y_hat_g = g_mod.predict(X_test)
    
    # get error metric
    if len(y_test) == 1:
        g_s_e = np.absolute([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    else:
        g_s_e = np.std([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    
    # update results
    oos_residuals_CV.loc[i] = np.asarray([g_s_e, K])
    
# output results
oos_residuals_CV
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>standard_error</th>
      <th>K</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>3.672747</td>
      <td>2.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>3.954330</td>
      <td>5.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3.224956</td>
      <td>10.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>7.383997</td>
      <td>50.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>1.272782</td>
      <td>25.0</td>
    </tr>
  </tbody>
</table>
</div>



There is still an effect of the one random fold. Let's do this many times and look at the distribution just like before.


```python
# constants
Nsim_per_K = 500 # simulations per K fold
num_Kuniques = len(Kuniques)
Ks = Kuniques * Nsim_per_K
n = len(y)

oos_residuals = pd.DataFrame({'standard_error': [0 for i in range(Nsim_per_K * num_Kuniques)],
                        'K': [0 for i in range(Nsim_per_K * num_Kuniques)]})

for i in range(len(Ks)):
    # constants
    K = Ks[i]
    prop_train = (K - 1) / K
    n_train = int(prop_train * n)

    # train test split indices
    indices = set([i for i in range(n)])
    train_index = set(random.sample(indices, n_train))
    test_index = indices - train_index
    
    # cast as lists
    train_index = list(train_index)
    test_index = list(test_index)

    # split based on indices
    X_train = pd.DataFrame([x[i] for i in train_index])
    y_train = pd.DataFrame([y[i] for i in train_index])

    X_test = pd.DataFrame([x[i] for i in test_index])
    y_test = pd.DataFrame([y[i] for i in test_index])

    # fitting model
    g_mod = LinearRegression().fit(X_train, y_train)
    
    # get predictions
    y_hat_g = g_mod.predict(X_test)
    
    # get error metric
    if len(y_test) == 1:
        g_s_e = np.absolute([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    else:
        g_s_e = np.std([float(y_test.iloc[i]) - y_hat_g[i] for i in range(len(y_test))])
    
    # update results
    oos_residuals.loc[i] = np.asarray([g_s_e, K])
    
# output results
oos_residuals
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>standard_error</th>
      <th>K</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>4.185499</td>
      <td>2.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>4.193835</td>
      <td>5.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3.317849</td>
      <td>10.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2.990152</td>
      <td>50.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>0.089897</td>
      <td>25.0</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>2495</th>
      <td>4.207371</td>
      <td>2.0</td>
    </tr>
    <tr>
      <th>2496</th>
      <td>3.761627</td>
      <td>5.0</td>
    </tr>
    <tr>
      <th>2497</th>
      <td>5.222147</td>
      <td>10.0</td>
    </tr>
    <tr>
      <th>2498</th>
      <td>5.706351</td>
      <td>50.0</td>
    </tr>
    <tr>
      <th>2499</th>
      <td>3.677768</td>
      <td>25.0</td>
    </tr>
  </tbody>
</table>
<p>2500 rows × 2 columns</p>
</div>



What is the variability?


```python
# mean of the standard errors grouped by K
oos_results_summary = pd.DataFrame({'K': list(oos_residuals.groupby(['K']).mean().index),
                                 'K_avg': list(oos_residuals.groupby(['K']).mean()['standard_error']),
                                 'K_SE': list(oos_residuals.groupby(['K']).std()['standard_error'])
                                }).set_index('K')

oos_results_summary
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>K_avg</th>
      <th>K_SE</th>
    </tr>
    <tr>
      <th>K</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2.0</th>
      <td>4.146039</td>
      <td>0.395974</td>
    </tr>
    <tr>
      <th>5.0</th>
      <td>3.877967</td>
      <td>0.579897</td>
    </tr>
    <tr>
      <th>10.0</th>
      <td>3.546045</td>
      <td>1.018892</td>
    </tr>
    <tr>
      <th>25.0</th>
      <td>2.368054</td>
      <td>1.752468</td>
    </tr>
    <tr>
      <th>50.0</th>
      <td>3.727671</td>
      <td>1.949647</td>
    </tr>
  </tbody>
</table>
</div>




```python
sns.displot(oos_residuals,
             x = 'standard_error',
             hue = 'K',
             kind = 'kde',
             multiple="stack",
             palette = 'bright',
             alpha = 0.9,
             aspect = 1.5) # width = height * aspect

plt.axvline(label='Mean 2.0', x=oos_results_summary.iloc[0, 0], color='blue')
plt.axvline(label='Mean 5.0', x=oos_results_summary.iloc[1, 0], color='orange')
plt.axvline(label='Mean 10.0', x=oos_results_summary.iloc[2, 0], color='green')
plt.axvline(label='Mean 25.0', x=oos_results_summary.iloc[3, 0], color='red')
plt.axvline(label='Mean 50.0', x=oos_results_summary.iloc[4, 0], color='purple')
plt.axvline(label='CV', x=oos_cross_validation_residual_average, color='black')

```

Admittedly, I don't know the properties of CV estimates as well as I should. Thus, there will be only procedural questions on the next exam. I do know that selecting K "optimally" for general datasets is an open question.

There is one other nice thing about having folds, you can estimate the standard error in your generalization estimate by pretending you have K iid samples and pretending the normal theory applies. For example, let's say K = 5. Instead of aggregating all residuals, we leave them separate and get K = 5 difference estimates for generalization error.


```python
# importing dependencies
from sklearn.model_selection import KFold

# initializing model
model = LinearRegression() # intercept will fit by default

# 10 folds
K = 10
kf = KFold(n_splits=K)

# list to hold residuals
oos_cross_validation_residuals = []

for train_index , test_index in kf.split(x):
    X_train = pd.DataFrame([x[i] for i in train_index])
    y_train = pd.DataFrame([y[i] for i in train_index])

    X_test = pd.DataFrame([x[i] for i in test_index])
    y_test = pd.DataFrame([y[i] for i in test_index])
    
    model.fit(X_train,y_train)
    y_hat_g = model.predict(X_test)
     
    oos_cross_validation_residuals += [np.std(y_test - y_hat_g)]
    
oos_cross_validation_residual_mean = np.mean(oos_cross_validation_residuals)
print(oos_cross_validation_residual_mean)

oos_cross_validation_residual_std = np.std(oos_cross_validation_residuals)
print(oos_cross_validation_residual_std)
```

    3.950922846645746
    0.8584252859259888



```python
# calculating confidence interval
import scipy.stats as st

confidence_interval = st.t.interval(alpha = 0.95,
                                   df = len(y) - 1,
                                   loc = oos_cross_validation_residual_mean,
                                   scale = oos_cross_validation_residual_std)

print(confidence_interval)
print(min(y), max(y))
```

    (2.2258526513895607, 5.675993041901931)
    1.2627430676861833 48.69439853538999


Although this is technically nonsense since they're not iid samples since the training set is crossed over containing mostly the same observations, at least it's something. In the above example, we've managed to capture the true generalization error.

Coverage in this confidence interval is over D. So I wouldn't gain much insight by simulating different splits with the same K.

I believe confidence intervals for generalization error is an open problem or maybe proved that you can't find them in general situations.

Here's a real data example with the `breast_cancer` dataset.


```python
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer(as_frame = True)
df = data.frame
X = df.iloc[:,:-1]
y = df.iloc[:,-1]

X
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>mean radius</th>
      <th>mean texture</th>
      <th>mean perimeter</th>
      <th>mean area</th>
      <th>mean smoothness</th>
      <th>mean compactness</th>
      <th>mean concavity</th>
      <th>mean concave points</th>
      <th>mean symmetry</th>
      <th>mean fractal dimension</th>
      <th>...</th>
      <th>worst radius</th>
      <th>worst texture</th>
      <th>worst perimeter</th>
      <th>worst area</th>
      <th>worst smoothness</th>
      <th>worst compactness</th>
      <th>worst concavity</th>
      <th>worst concave points</th>
      <th>worst symmetry</th>
      <th>worst fractal dimension</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>17.99</td>
      <td>10.38</td>
      <td>122.80</td>
      <td>1001.0</td>
      <td>0.11840</td>
      <td>0.27760</td>
      <td>0.30010</td>
      <td>0.14710</td>
      <td>0.2419</td>
      <td>0.07871</td>
      <td>...</td>
      <td>25.380</td>
      <td>17.33</td>
      <td>184.60</td>
      <td>2019.0</td>
      <td>0.16220</td>
      <td>0.66560</td>
      <td>0.7119</td>
      <td>0.2654</td>
      <td>0.4601</td>
      <td>0.11890</td>
    </tr>
    <tr>
      <th>1</th>
      <td>20.57</td>
      <td>17.77</td>
      <td>132.90</td>
      <td>1326.0</td>
      <td>0.08474</td>
      <td>0.07864</td>
      <td>0.08690</td>
      <td>0.07017</td>
      <td>0.1812</td>
      <td>0.05667</td>
      <td>...</td>
      <td>24.990</td>
      <td>23.41</td>
      <td>158.80</td>
      <td>1956.0</td>
      <td>0.12380</td>
      <td>0.18660</td>
      <td>0.2416</td>
      <td>0.1860</td>
      <td>0.2750</td>
      <td>0.08902</td>
    </tr>
    <tr>
      <th>2</th>
      <td>19.69</td>
      <td>21.25</td>
      <td>130.00</td>
      <td>1203.0</td>
      <td>0.10960</td>
      <td>0.15990</td>
      <td>0.19740</td>
      <td>0.12790</td>
      <td>0.2069</td>
      <td>0.05999</td>
      <td>...</td>
      <td>23.570</td>
      <td>25.53</td>
      <td>152.50</td>
      <td>1709.0</td>
      <td>0.14440</td>
      <td>0.42450</td>
      <td>0.4504</td>
      <td>0.2430</td>
      <td>0.3613</td>
      <td>0.08758</td>
    </tr>
    <tr>
      <th>3</th>
      <td>11.42</td>
      <td>20.38</td>
      <td>77.58</td>
      <td>386.1</td>
      <td>0.14250</td>
      <td>0.28390</td>
      <td>0.24140</td>
      <td>0.10520</td>
      <td>0.2597</td>
      <td>0.09744</td>
      <td>...</td>
      <td>14.910</td>
      <td>26.50</td>
      <td>98.87</td>
      <td>567.7</td>
      <td>0.20980</td>
      <td>0.86630</td>
      <td>0.6869</td>
      <td>0.2575</td>
      <td>0.6638</td>
      <td>0.17300</td>
    </tr>
    <tr>
      <th>4</th>
      <td>20.29</td>
      <td>14.34</td>
      <td>135.10</td>
      <td>1297.0</td>
      <td>0.10030</td>
      <td>0.13280</td>
      <td>0.19800</td>
      <td>0.10430</td>
      <td>0.1809</td>
      <td>0.05883</td>
      <td>...</td>
      <td>22.540</td>
      <td>16.67</td>
      <td>152.20</td>
      <td>1575.0</td>
      <td>0.13740</td>
      <td>0.20500</td>
      <td>0.4000</td>
      <td>0.1625</td>
      <td>0.2364</td>
      <td>0.07678</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>564</th>
      <td>21.56</td>
      <td>22.39</td>
      <td>142.00</td>
      <td>1479.0</td>
      <td>0.11100</td>
      <td>0.11590</td>
      <td>0.24390</td>
      <td>0.13890</td>
      <td>0.1726</td>
      <td>0.05623</td>
      <td>...</td>
      <td>25.450</td>
      <td>26.40</td>
      <td>166.10</td>
      <td>2027.0</td>
      <td>0.14100</td>
      <td>0.21130</td>
      <td>0.4107</td>
      <td>0.2216</td>
      <td>0.2060</td>
      <td>0.07115</td>
    </tr>
    <tr>
      <th>565</th>
      <td>20.13</td>
      <td>28.25</td>
      <td>131.20</td>
      <td>1261.0</td>
      <td>0.09780</td>
      <td>0.10340</td>
      <td>0.14400</td>
      <td>0.09791</td>
      <td>0.1752</td>
      <td>0.05533</td>
      <td>...</td>
      <td>23.690</td>
      <td>38.25</td>
      <td>155.00</td>
      <td>1731.0</td>
      <td>0.11660</td>
      <td>0.19220</td>
      <td>0.3215</td>
      <td>0.1628</td>
      <td>0.2572</td>
      <td>0.06637</td>
    </tr>
    <tr>
      <th>566</th>
      <td>16.60</td>
      <td>28.08</td>
      <td>108.30</td>
      <td>858.1</td>
      <td>0.08455</td>
      <td>0.10230</td>
      <td>0.09251</td>
      <td>0.05302</td>
      <td>0.1590</td>
      <td>0.05648</td>
      <td>...</td>
      <td>18.980</td>
      <td>34.12</td>
      <td>126.70</td>
      <td>1124.0</td>
      <td>0.11390</td>
      <td>0.30940</td>
      <td>0.3403</td>
      <td>0.1418</td>
      <td>0.2218</td>
      <td>0.07820</td>
    </tr>
    <tr>
      <th>567</th>
      <td>20.60</td>
      <td>29.33</td>
      <td>140.10</td>
      <td>1265.0</td>
      <td>0.11780</td>
      <td>0.27700</td>
      <td>0.35140</td>
      <td>0.15200</td>
      <td>0.2397</td>
      <td>0.07016</td>
      <td>...</td>
      <td>25.740</td>
      <td>39.42</td>
      <td>184.60</td>
      <td>1821.0</td>
      <td>0.16500</td>
      <td>0.86810</td>
      <td>0.9387</td>
      <td>0.2650</td>
      <td>0.4087</td>
      <td>0.12400</td>
    </tr>
    <tr>
      <th>568</th>
      <td>7.76</td>
      <td>24.54</td>
      <td>47.92</td>
      <td>181.0</td>
      <td>0.05263</td>
      <td>0.04362</td>
      <td>0.00000</td>
      <td>0.00000</td>
      <td>0.1587</td>
      <td>0.05884</td>
      <td>...</td>
      <td>9.456</td>
      <td>30.37</td>
      <td>59.16</td>
      <td>268.6</td>
      <td>0.08996</td>
      <td>0.06444</td>
      <td>0.0000</td>
      <td>0.0000</td>
      <td>0.2871</td>
      <td>0.07039</td>
    </tr>
  </tbody>
</table>
<p>569 rows × 30 columns</p>
</div>




```python
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold

k = 5
kf = KFold(n_splits=k, random_state=None)

model = LinearRegression()
 
residuals = []
 
for train_index , test_index in kf.split(X):
    X_train , X_test = X.iloc[train_index,:],X.iloc[test_index,:]
    y_train , y_test = y[train_index] , y[test_index]
     
    model.fit(X_train,y_train)
    y_hat_g = model.predict(X_test)
     
    residuals += [np.std(y_test - y_hat_g)]

print(np.mean(residuals))
print(np.std(residuals))
```

    0.24089771870604665
    0.03227633906367752



```python
# calculating confidence interval
import scipy.stats as st

confidence_interval = st.t.interval(alpha = 0.95,
                                   df = len(X) - 1,
                                   loc = np.mean(residuals),
                                   scale = np.std(residuals))

print(confidence_interval)
```

    (0.17750217054311385, 0.30429326686897945)


ffe1122acc07ce0e3e50829e32f557d227a04837
ipynb
Jupyter Notebook
Practice Notes/16 - Python Practice Lecture 16 MATH 342W Queens College - K-fold Cross Validation.ipynb
Hi-Tree/342-2022-Python-Practice-lectures
aaa2128a8e3009958ffd0636ceb424b2eecb938f
MIT
Practice Notes/16 - Python Practice Lecture 16 MATH 342W Queens College - K-fold Cross Validation.ipynb
Hi-Tree/342-2022-Python-Practice-lectures
aaa2128a8e3009958ffd0636ceb424b2eecb938f
MIT
Practice Notes/16 - Python Practice Lecture 16 MATH 342W Queens College - K-fold Cross Validation.ipynb
Hi-Tree/342-2022-Python-Practice-lectures
aaa2128a8e3009958ffd0636ceb424b2eecb938f
MIT
Qwen/Qwen-72B
1. YES
2. YES