Data splitting

Data preparation

In this series, we practice the data splitting strategies seen in class. The data are the doctor visits, already used in previous applications: cross-validation, bootstrap, and balancing.

We’ll be using the DocVis dataset for this lab session.

DocVis <- read.csv(here::here("labs/data/DocVis.csv"))
DocVis$visits <- as.factor(DocVis$visits) ## make sure that visits is a factor

We need to set aside a test set. This will be used after to check that there was no overfitting during the training of the model and to ensure that the score we have obtained generalizes outside the training data.

library(caret)
library(dplyr)
set.seed(346)
index_tr <- createDataPartition(y = DocVis$visits, p= 0.8, list = FALSE)
df_tr <- DocVis[index_tr,]
df_te <- DocVis[-index_tr,]

Note that the splitting techniques used are applied on the training set only.

10-fold Cross-validation

In this part, we practice the cross-validation by first building it “by hand” then in an automatic way using caret. A 10-fold cross-validation is prepared.

First fold

First, we create the folds by using the createFolds function of caret.

index_CV <- createFolds(y = df_tr$visits, k=10)
index_CV[[1]]
  [1]    1    3   13   18   20   27   30   37   51   93  102  104  111  133  139
 [16]  141  142  153  165  172  179  197  206  207  233  242  288  293  299  304
 [31]  357  369  387  430  431  440  446  450  455  474  488  497  502  512  521
 [46]  538  539  540  543  571  579  583  594  625  632  638  641  651  653  657
 [61]  678  693  699  705  707  711  722  726  729  732  735  745  747  749  761
 [76]  763  788  796  799  806  808  818  820  829  849  862  886  894  900  904
 [91]  906  909  921  926  960  963  982  990  992  993 1000 1001 1008 1009 1016
[106] 1025 1031 1041 1056 1062 1081 1088 1093 1099 1123 1137 1144 1149 1152 1157
[121] 1167 1171 1183 1188 1193 1194 1219 1220 1231 1238 1260 1277 1292 1296 1302
[136] 1323 1330 1340 1341 1348 1353 1358 1361 1364 1384 1391 1416 1420 1431 1438
[151] 1447 1450 1482 1497 1502 1504 1515 1567 1574 1588 1612 1620 1637 1648 1658
[166] 1660 1663 1665 1670 1671 1679 1688 1700 1702 1732 1742 1747 1749 1768 1770
[181] 1776 1798 1800 1805 1808 1828 1829 1845 1858 1862 1890 1893 1912 1918 1920
[196] 1921 1927 1943 1952 1957 1997 2010 2015 2026 2036 2039 2042 2063 2067 2088
[211] 2113 2118 2124 2139 2147 2155 2185 2195 2205 2216 2219 2246 2254 2256 2261
[226] 2263 2284 2296 2309 2336 2364 2366 2369 2372 2381 2404 2419 2422 2423 2429
[241] 2449 2456 2466 2505 2507 2547 2566 2569 2573 2585 2601 2608 2616 2620 2630
[256] 2635 2644 2674 2682 2683 2689 2691 2708 2715 2720 2727 2734 2738 2744 2758
[271] 2769 2772 2775 2780 2786 2791 2797 2798 2808 2814 2823 2829 2840 2863 2864
[286] 2877 2886 2892 2921 2926 2927 2957 2958 2962 2965 2971 2979 2985 2991 2997
[301] 2999 3005 3011 3016 3019 3038 3053 3080 3096 3099 3101 3111 3114 3119 3133
[316] 3142 3147 3157 3169 3212 3219 3247 3254 3265 3270 3279 3286 3293 3312 3316
[331] 3330 3345 3348 3358 3384 3400 3407 3413 3437 3438 3440 3442 3444 3453 3457
[346] 3461 3466 3471 3480 3493 3495 3502 3541 3543 3546 3567 3573 3576 3578 3589
[361] 3614 3615 3621 3623 3627 3632 3637 3642 3654 3680 3707 3715 3742 3748 3765
[376] 3766 3776 3794 3800 3803 3808 3813 3820 3834 3835 3838 3841 3856 3858 3871
[391] 3892 3893 3898 3899 3904 3908 3910 3933 3941 3958 3962 3978 3980 3995 4032
[406] 4055 4057 4074 4075 4084 4104 4106 4107 4108 4112

As seen before, the index_CV object is a list of row indices. The first element of the list index_CV[[1]] corresponds to the first fold. It is the vector of row indices of the validation set for the first fold (i.e., the validation is made of the rows of the training set that are in this vector). All the indices that are not in index_CV[[1]] will be in the training set (for this fold).

df_cv_tr <- df_tr[-index_CV[[1]],]
df_cv_val <- df_tr[index_CV[[1]],]

For this fold, df_cv_tr is the training set (it contains 9/10 of the original training set df_tr) and df_cv_val is the validation set (it contains 1/10 of the original training set df_tr). These two sets are disjoints.

Now, we simply fit the model with the training set and compute its accuracy on the validation set. For this exercise, we use a logistic regression with AIC-based variable selection.

Doc_cv <- glm(visits~., data=df_cv_tr, family="binomial") %>% step()
Doc_cv_prob <- predict(Doc_cv, newdata=df_cv_val, type="response")
Doc_cv_pred <- ifelse(Doc_cv_prob>0.5,"Yes","No")
confusionMatrix(data=as.factor(Doc_cv_pred), reference = df_cv_val$visits)$overall[1]
Start:  AIC=3284.47
visits ~ gender + age + income + illness + reduced + health + 
    private + freepoor + freerepat + nchronic + lchronic

            Df Deviance    AIC
- nchronic   1   3260.5 3282.5
- income     1   3261.0 3283.0
<none>           3260.5 3284.5
- freerepat  1   3264.0 3286.0
- private    1   3264.7 3286.7
- lchronic   1   3265.9 3287.9
- age        1   3266.3 3288.3
- health     1   3267.5 3289.5
- gender     1   3268.4 3290.4
- freepoor   1   3273.1 3295.1
- illness    1   3321.5 3343.5
- reduced    1   3406.0 3428.0

Step:  AIC=3282.52
visits ~ gender + age + income + illness + reduced + health + 
    private + freepoor + freerepat + lchronic

            Df Deviance    AIC
- income     1   3261.1 3281.1
<none>           3260.5 3282.5
- freerepat  1   3264.1 3284.1
- private    1   3264.8 3284.8
- lchronic   1   3266.9 3286.9
- age        1   3267.0 3287.0
- health     1   3267.6 3287.6
- gender     1   3268.6 3288.6
- freepoor   1   3273.1 3293.1
- illness    1   3327.6 3347.6
- reduced    1   3406.0 3426.0

Step:  AIC=3281.08
visits ~ gender + age + illness + reduced + health + private + 
    freepoor + freerepat + lchronic

            Df Deviance    AIC
<none>           3261.1 3281.1
- private    1   3265.0 3283.0
- freerepat  1   3265.2 3283.2
- lchronic   1   3267.4 3285.4
- age        1   3268.1 3286.1
- health     1   3268.3 3286.3
- gender     1   3270.5 3288.5
- freepoor   1   3273.1 3291.1
- illness    1   3328.8 3346.8
- reduced    1   3406.4 3424.4
 Accuracy 
0.8048193 
# Load the course python environment as usual with a r code chunks.
library(reticulate)
use_condaenv("MLBA", required = TRUE)

We will one-hot encode the categorical variables using pd.get_dummies() and then divide the data into X_train, y_train, X_test and y_test.

import pandas as pd

# One-hot encoding the categorical columns
X_train = pd.get_dummies(r.df_tr.drop('visits', axis=1))
y_train = r.df_tr['visits']
X_test = pd.get_dummies(r.df_te.drop('visits', axis=1))
y_test = r.df_te['visits']

Then, we create the folds by using the KFold function of scikit-learn.

from sklearn.model_selection import KFold
# We setup the 10-k fold
kf = KFold(n_splits=10, random_state=346, shuffle=True)
fold_indices = list(kf.split(X_train, y_train))
first_fold_train, first_fold_val = fold_indices[0]

As seen before, the fold_indices object is a list of tuple pairs. The first element of the list fold_indices[0] corresponds to the first fold. It is the tuple of row indices of the training set and the validation set for the first fold. All the indices that are not in first_fold_val will be in the training set (for this fold).

X_cv_tr = X_train.iloc[first_fold_train, :]
y_cv_tr = y_train.iloc[first_fold_train]

X_cv_val = X_train.iloc[first_fold_val, :]
y_cv_val = y_train.iloc[first_fold_val]

This part, will be slightly different from the R approach. Here, we fit the model with the training set and compute its accuracy on the validation set. For the python approach, we use a logistic regression with recursive feature elimination to select the best number of features.

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.feature_selection import RFE
import numpy as np

model = LogisticRegression(solver='liblinear')
rfe = RFE(model)
rfe.fit(X_cv_tr, y_cv_tr);
pred_probs = rfe.predict_proba(X_cv_val)[:, 1]
Doc_cv_pred = np.where(pred_probs > 0.5, "Yes", "No")
acc = accuracy_score(y_cv_val, Doc_cv_pred)
acc

# alternatively, you could use `cross_val_score`
# from sklearn.model_selection import cross_val_score
# cv_scores = cross_val_score(rfe, X_cv_tr, y_cv_tr, cv=kf, scoring="accuracy")
# cv_scores
0.7980769230769231

Loop on the 10 folds

Now we repeat the previous steps for all the folds.

In order to track the 10 accuracy measures obtained, we store them into a vector (acc_vec). Note also that the option trace=0 was set in the function step to avoid all the print outs of the AIC selections.

acc_vec <- numeric(10)
for (i in 1:10){
  df_cv_tr <- df_tr[-index_CV[[i]],]
  df_cv_val <- df_tr[index_CV[[i]],]
  
  Doc_cv <- glm(visits~., data=df_cv_tr, family="binomial") %>% step(trace=0)
  Doc_cv_prob <- predict(Doc_cv, newdata=df_cv_val, type="response")
  Doc_cv_pred <- ifelse(Doc_cv_prob>0.5,"Yes","No")
  acc_vec[i] <- confusionMatrix(data=as.factor(Doc_cv_pred), reference = df_cv_val$visits)$overall[1]
}
acc_vec
 [1] 0.8048193 0.8149038 0.8028846 0.8265060 0.7951807 0.8096386 0.7903614
 [8] 0.8144578 0.8048193 0.8149038

By definition of the CV, all the 10 validations sets in this loop are disjoints. Thus, these 10 accuracy measures are in a way representative of what can be expected on the test set, except if we are very unlucky when we created the test set.

Now we can estimate the expected accuracy (i.e., the mean) and its variation (below we use the standard deviation).

mean(acc_vec)
sd(acc_vec)
[1] 0.8078475
[1] 0.01056098

The small SD shows that the results are reliable and that we have good chance that the model, trained on the whole training set, will have this accuracy on the test set.

For python, in order to track the 10 accuracy measures obtained, we store them into a list (acc_list).

acc_list = []
for train_idx, val_idx in kf.split(X_train, y_train):
    X_cv_tr, y_cv_tr = X_train.iloc[train_idx, :], y_train.iloc[train_idx]
    X_cv_val, y_cv_val = X_train.iloc[val_idx, :], y_train.iloc[val_idx]
    
    rfe.fit(X_cv_tr, y_cv_tr);
    pred_probs = rfe.predict_proba(X_cv_val)[:, 1]
    Doc_cv_pred = np.where(pred_probs > 0.5, "Yes", "No")
    acc = accuracy_score(y_cv_val, Doc_cv_pred)
    acc_list.append(acc)
acc_list
RFE(estimator=LogisticRegression(solver='liblinear'))
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
[0.7980769230769231, 0.7548076923076923, 0.7668269230769231, 0.8120481927710843, 0.7975903614457831, 0.7951807228915663, 0.8240963855421687, 0.8168674698795181, 0.7951807228915663, 0.7951807228915663]

Once again, we can estimate the expected accuracy and its variation.

mean_acc = np.mean(acc_list)
std_acc = np.std(acc_list)
mean_acc, std_acc
(np.float64(0.7955856116774791), np.float64(0.02009332383708743))

Now, we fit the final model using the whole training set and evaluate its performance on the test set.

rfe.fit(X_train, y_train);
y_test_pred = rfe.predict(X_test)
test_accuracy = accuracy_score(y_test, y_test_pred)
test_cm = confusion_matrix(y_test, y_test_pred)
test_accuracy, test_cm
(0.8032786885245902, array([[810,  18],
       [186,  23]]))

Automated approach

The 10-CV can be easily obtained from caret. First, set up the splitting data method using the trainControl function.

trctrl <- trainControl(method = "cv", number=10)

Then pass this method to the train function (from caret). In addition, we use the model (below unhappily called “method” also) glmStepAIC which, combined with the binomial family, applies a logistic regression and a AIC-based variable selection (backward; exactly like the step function used above). Of course, we also provide the model formula.

set.seed(346)
Doc_cv <- train(visits ~., data = df_tr, method = "glmStepAIC", family="binomial",
                    trControl=trctrl, trace=0)
Doc_cv
Generalized Linear Model with Stepwise Feature Selection 

4153 samples
  11 predictor
   2 classes: 'No', 'Yes' 

No pre-processing
Resampling: Cross-Validated (10 fold) 
Summary of sample sizes: 3737, 3737, 3738, 3738, 3738, 3737, ... 
Resampling results:

  Accuracy  Kappa    
  0.809057  0.1944424

Note that the function “only” provides the expected accuracy and the expected kappa. It does not provides their standard deviations.

The final model (i.e., the model trained on the whole training set df_tr) is stored in Doc_cv$finalModel. It can be used to compute the accuracy on the test set.

Doc_pred <- predict(Doc_cv, newdata = df_te)
confusionMatrix(data=Doc_pred, reference = df_te$visits)
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  809 179
       Yes  19  30
                                          
               Accuracy : 0.8091          
                 95% CI : (0.7838, 0.8326)
    No Information Rate : 0.7985          
    P-Value [Acc > NIR] : 0.2089          
                                          
                  Kappa : 0.1689          
                                          
 Mcnemar's Test P-Value : <2e-16          
                                          
            Sensitivity : 0.9771          
            Specificity : 0.1435          
         Pos Pred Value : 0.8188          
         Neg Pred Value : 0.6122          
             Prevalence : 0.7985          
         Detection Rate : 0.7801          
   Detection Prevalence : 0.9527          
      Balanced Accuracy : 0.5603          
                                          
       'Positive' Class : No              
                                          

In python, a similar approach demonstrated in caret would be using GridSearchCV from scikit-learn. We use the same 10-CV kf object created earlier. Then pass this method to the GridSearchCV function with LogisticRegression model with RFE for feature selection with the grid of parameters we would like to search for (in this case the number of features). Then, we output the (hyper-)parameters with the best performance.

from sklearn.model_selection import GridSearchCV

model = LogisticRegression(solver='liblinear')
rfe = RFE(model)
param_grid = {'n_features_to_select': list(range(1, X_train.shape[1] + 1))}
grid_search = GridSearchCV(rfe, param_grid, scoring='accuracy', cv=kf)
grid_search.fit(X_train, y_train);
print(grid_search.best_score_, grid_search.best_params_)
0.8085831788693234 {'n_features_to_select': 17}

The final model (i.e., the model trained on the whole training set X_train) is stored in grid_search.best_estimator_. It can be used to compute the accuracy on the test set.

y_test_pred = grid_search.best_estimator_.predict(X_test)
test_accuracy = accuracy_score(y_test, y_test_pred)
test_cm = confusion_matrix(y_test, y_test_pred)
print(test_accuracy, test_cm)
0.8090646094503375 [[809  19]
 [179  30]]

Our results did improve compared to the last python model.

Bootstrap with 100 replicates

We now apply the bootstrap with 100 replicates. Like for CV, we first make it by hand and then we use some kind of automated approach like caret.

First sample

We need to first create the replicates using the caret function createResample.

set.seed(897)
index_boot <- createResample(y=df_tr$visits, times=100)
index_boot[[1]]
   [1]    1    1    2    3    4    5    6    6    9   11   13   13   14   14
  [15]   17   18   18   20   21   22   22   22   22   22   23   24   26   27
  [29]   27   28   29   30   32   32   34   34   35   35   36   36   36   37
  [43]   37   40   41   42   44   45   46   46   47   50   50   50   50   53
  [57]   54   55   57   57   59   59   60   60   62   62   65   66   67   68
  [71]   69   71   72   73   75   75   81   81   82   83   86   87   87   87
  [85]   88   88   90   90   90   91   92   92   92   93   98  100  100  101
  [99]  102  104  106  107  108  110  112  112  112  112  117  117  117  118
 [113]  118  122  124  125  125  126  128  128  128  129  130  131  132  133
 [127]  133  134  134  135  136  137  141  144  144  144  144  148  148  150
 [141]  150  151  152  154  156  156  157  157  158  159  159  160  161  162
 [155]  165  165  166  168  169  171  171  172  172  173  174  174  174  175
 [169]  177  178  179  180  180  180  184  185  186  188  189  189  189  189
 [183]  190  193  195  195  195  197  197  198  201  201  202  202  205  206
 [197]  208  208  208  209  209  209  210  213  213  213  214  216  216  217
 [211]  217  218  218  218  219  219  220  221  222  223  223  223  224  224
 [225]  225  226  226  226  229  229  229  229  232  235  235  236  237  237
 [239]  239  239  240  241  241  243  243  244  244  244  244  247  248  249
 [253]  252  253  255  257  257  257  258  258  262  263  263  265  266  266
 [267]  267  268  271  272  273  274  275  276  280  280  281  281  281  281
 [281]  282  282  285  285  287  287  287  288  288  290  290  293  294  295
 [295]  296  296  296  297  299  300  303  304  304  306  306  306  307  308
 [309]  309  309  309  311  312  314  315  315  317  318  319  319  320  320
 [323]  321  322  325  326  326  328  328  332  333  333  334  335  337  338
 [337]  339  340  340  340  341  341  342  342  343  344  346  348  349  360
 [351]  363  365  369  369  371  371  372  372  372  373  373  373  374  374
 [365]  374  374  376  379  380  381  382  382  383  384  384  387  388  389
 [379]  394  398  399  399  400  404  405  407  408  408  412  415  415  416
 [393]  416  417  420  420  422  422  425  425  427  427  427  429  429  431
 [407]  432  433  434  434  434  434  434  439  441  444  446  446  446  447
 [421]  448  448  449  450  450  451  452  453  453  457  458  459  460  460
 [435]  463  466  467  467  468  469  470  471  471  471  473  474  476  477
 [449]  478  478  480  482  483  483  483  483  487  487  488  489  490  490
 [463]  490  491  492  494  494  494  494  497  498  498  499  499  500  500
 [477]  502  502  502  503  504  504  505  506  506  507  508  508  510  511
 [491]  511  512  514  515  516  517  518  518  518  518  519  519  522  522
 [505]  522  524  526  526  527  530  531  532  533  534  535  535  538  538
 [519]  539  540  542  543  545  545  546  547  549  551  552  552  552  553
 [533]  554  554  555  556  557  557  559  562  562  564  564  565  565  567
 [547]  570  573  575  577  578  579  580  581  581  581  582  583  583  584
 [561]  584  588  593  593  595  595  596  596  597  598  598  599  600  600
 [575]  600  601  601  602  603  603  605  605  605  605  607  607  608  608
 [589]  611  612  615  616  616  617  617  618  619  620  620  620  622  622
 [603]  623  625  628  634  635  636  637  637  638  640  640  641  641  643
 [617]  644  645  646  647  648  649  650  651  651  651  652  652  653  653
 [631]  653  654  656  656  657  657  657  658  659  660  661  661  662  663
 [645]  663  663  663  664  665  666  666  666  668  668  670  670  671  672
 [659]  673  674  675  676  677  678  678  679  679  680  680  680  680  680
 [673]  681  681  682  683  683  684  685  685  686  686  688  688  688  690
 [687]  691  691  694  697  697  697  698  701  701  701  702  703  704  704
 [701]  704  705  706  707  707  707  708  709  709  710  711  711  711  712
 [715]  715  715  720  720  721  722  722  723  724  724  725  728  728  728
 [729]  729  729  731  732  734  734  735  735  736  737  739  739  739  741
 [743]  742  742  744  745  746  749  750  751  755  755  755  755  756  756
 [757]  757  757  758  759  761  762  764  764  765  766  766  768  768  770
 [771]  770  772  772  772  773  774  775  778  779  780  780  781  783  784
 [785]  785  787  787  787  789  789  792  794  794  795  795  795  795  797
 [799]  797  798  798  799  800  801  802  804  805  805  806  806  806  807
 [813]  807  809  809  810  813  813  814  816  816  818  822  823  823  824
 [827]  825  827  827  827  828  829  829  829  831  831  832  834  835  836
 [841]  837  837  838  839  840  841  842  844  846  847  847  849  849  849
 [855]  852  855  855  855  856  857  858  858  859  860  862  863  865  865
 [869]  866  866  868  869  870  870  871  871  871  871  878  878  879  880
 [883]  880  880  880  882  884  884  885  885  887  887  887  888  888  888
 [897]  889  890  890  891  891  894  895  896  898  898  899  901  901  902
 [911]  906  907  909  909  909  910  910  910  915  915  916  917  918  918
 [925]  921  921  924  925  926  926  927  927  927  929  930  930  931  931
 [939]  932  932  932  933  934  934  934  934  937  938  940  941  942  942
 [953]  944  944  944  944  946  948  948  949  950  952  952  955  956  958
 [967]  959  959  962  963  963  963  965  965  966  967  968  970  971  972
 [981]  972  974  979  979  981  981  982  983  984  987  988  992  992  993
 [995]  993  994  996  997  997  999 1000 1000 1001 1002 1003 1005 1005 1005
[1009] 1006 1007 1008 1009 1009 1009 1010 1012 1013 1014 1014 1014 1015 1015
[1023] 1015 1017 1018 1020 1022 1025 1026 1030 1034 1035 1035 1035 1036 1038
[1037] 1038 1038 1039 1042 1042 1042 1043 1044 1045 1045 1046 1046 1048 1048
[1051] 1050 1052 1055 1055 1055 1057 1057 1057 1059 1061 1061 1062 1063 1065
[1065] 1066 1067 1067 1068 1068 1068 1069 1070 1070 1074 1074 1075 1077 1079
[1079] 1080 1081 1083 1083 1084 1084 1085 1086 1086 1086 1088 1089 1089 1089
[1093] 1093 1095 1096 1096 1098 1098 1100 1100 1104 1106 1107 1108 1111 1111
[1107] 1113 1114 1114 1114 1115 1115 1115 1117 1117 1118 1120 1122 1122 1122
[1121] 1123 1123 1124 1126 1126 1126 1129 1129 1130 1130 1131 1132 1133 1134
[1135] 1134 1136 1140 1142 1142 1143 1144 1149 1150 1150 1150 1152 1152 1154
[1149] 1156 1157 1162 1163 1165 1172 1174 1174 1176 1176 1181 1182 1182 1187
[1163] 1187 1187 1187 1190 1190 1192 1193 1195 1195 1195 1196 1197 1197 1198
[1177] 1200 1202 1202 1204 1204 1204 1206 1208 1208 1212 1213 1215 1215 1215
[1191] 1215 1216 1216 1216 1217 1217 1219 1220 1221 1221 1222 1222 1222 1223
[1205] 1224 1224 1225 1226 1228 1229 1229 1231 1231 1231 1232 1232 1233 1233
[1219] 1234 1235 1235 1235 1236 1236 1238 1239 1240 1241 1242 1243 1247 1247
[1233] 1248 1248 1250 1250 1251 1252 1252 1253 1256 1258 1260 1260 1262 1262
[1247] 1263 1264 1265 1266 1270 1270 1271 1271 1271 1271 1273 1274 1276 1280
[1261] 1282 1282 1282 1282 1282 1282 1284 1285 1287 1287 1287 1288 1290 1290
[1275] 1292 1292 1294 1296 1297 1299 1299 1300 1301 1302 1303 1306 1307 1307
[1289] 1309 1309 1309 1310 1310 1311 1311 1311 1312 1313 1313 1313 1313 1313
[1303] 1317 1317 1318 1320 1321 1323 1324 1325 1328 1330 1331 1332 1333 1335
[1317] 1336 1336 1338 1339 1340 1344 1344 1344 1345 1350 1350 1350 1353 1354
[1331] 1355 1356 1356 1357 1358 1359 1359 1359 1359 1359 1359 1360 1360 1360
[1345] 1361 1362 1362 1363 1364 1365 1365 1367 1367 1368 1370 1371 1371 1371
[1359] 1371 1372 1373 1374 1377 1377 1379 1379 1382 1383 1384 1388 1389 1391
[1373] 1392 1392 1392 1393 1394 1394 1394 1396 1397 1397 1397 1398 1402 1403
[1387] 1403 1403 1404 1404 1404 1406 1406 1409 1409 1409 1411 1411 1412 1415
[1401] 1417 1417 1420 1420 1422 1423 1423 1424 1424 1425 1426 1428 1429 1430
[1415] 1432 1433 1433 1434 1434 1434 1435 1436 1438 1441 1442 1442 1442 1442
[1429] 1443 1443 1444 1444 1444 1445 1445 1445 1446 1448 1449 1449 1450 1451
[1443] 1456 1456 1458 1459 1461 1461 1462 1462 1465 1465 1466 1466 1468 1470
[1457] 1471 1472 1474 1474 1475 1475 1475 1476 1477 1477 1480 1481 1482 1482
[1471] 1483 1483 1484 1484 1485 1486 1487 1488 1489 1490 1490 1491 1493 1495
[1485] 1496 1497 1497 1498 1499 1500 1501 1501 1501 1503 1504 1505 1505 1505
[1499] 1506 1508 1509 1510 1512 1512 1514 1514 1515 1516 1516 1517 1518 1518
[1513] 1519 1520 1521 1521 1525 1525 1526 1530 1537 1537 1542 1543 1543 1544
[1527] 1544 1544 1544 1545 1546 1547 1549 1550 1550 1552 1555 1555 1556 1556
[1541] 1557 1558 1562 1562 1564 1564 1566 1567 1567 1568 1568 1568 1569 1569
[1555] 1572 1572 1573 1573 1574 1577 1578 1579 1579 1579 1580 1582 1584 1584
[1569] 1587 1587 1588 1588 1589 1590 1591 1593 1594 1595 1596 1597 1597 1600
[1583] 1601 1601 1602 1604 1606 1608 1608 1608 1608 1608 1610 1614 1615 1616
[1597] 1618 1620 1621 1623 1624 1625 1626 1626 1628 1629 1630 1630 1631 1633
[1611] 1633 1634 1634 1635 1635 1636 1637 1639 1639 1640 1640 1641 1642 1644
[1625] 1645 1645 1646 1649 1650 1650 1650 1650 1652 1652 1652 1653 1653 1656
[1639] 1657 1658 1659 1660 1665 1667 1667 1667 1670 1673 1674 1675 1677 1678
[1653] 1679 1679 1680 1680 1681 1681 1683 1686 1686 1687 1687 1688 1688 1688
[1667] 1689 1689 1689 1690 1693 1694 1695 1696 1697 1697 1698 1698 1698 1699
[1681] 1700 1701 1704 1706 1706 1706 1710 1712 1713 1714 1715 1717 1718 1719
[1695] 1720 1723 1723 1725 1725 1725 1726 1728 1730 1730 1732 1733 1735 1736
[1709] 1737 1739 1739 1739 1739 1741 1741 1741 1741 1742 1743 1743 1745 1746
[1723] 1749 1749 1751 1752 1752 1753 1754 1755 1756 1756 1760 1762 1763 1765
[1737] 1766 1766 1767 1768 1769 1769 1770 1771 1771 1772 1773 1774 1775 1775
[1751] 1776 1778 1779 1779 1783 1784 1787 1787 1787 1788 1788 1788 1790 1794
[1765] 1794 1794 1795 1795 1795 1798 1798 1799 1800 1800 1802 1805 1808 1808
[1779] 1808 1810 1811 1812 1816 1818 1818 1820 1822 1823 1824 1826 1827 1832
[1793] 1832 1833 1834 1835 1836 1838 1838 1839 1839 1842 1843 1844 1846 1846
[1807] 1847 1847 1849 1849 1851 1852 1853 1854 1855 1855 1856 1856 1858 1858
[1821] 1859 1859 1860 1861 1861 1861 1864 1865 1865 1866 1867 1868 1868 1869
[1835] 1869 1869 1869 1870 1871 1876 1876 1877 1878 1878 1878 1878 1878 1880
[1849] 1881 1882 1882 1883 1884 1885 1889 1891 1892 1892 1893 1895 1895 1896
[1863] 1897 1899 1901 1902 1905 1905 1905 1907 1908 1910 1910 1912 1912 1914
[1877] 1915 1917 1918 1919 1919 1922 1925 1926 1928 1932 1934 1934 1937 1938
[1891] 1939 1939 1942 1947 1950 1950 1950 1950 1950 1951 1952 1952 1952 1952
[1905] 1954 1955 1955 1958 1958 1959 1960 1960 1960 1960 1960 1960 1961 1962
[1919] 1965 1965 1966 1968 1968 1968 1968 1969 1970 1971 1972 1972 1974 1974
[1933] 1975 1975 1979 1979 1981 1981 1982 1982 1983 1983 1985 1986 1987 1989
[1947] 1989 1989 1991 1991 1992 1993 1994 1994 1995 1995 1995 1997 1997 1997
[1961] 1998 1998 1998 2003 2003 2004 2008 2009 2010 2011 2011 2011 2012 2014
[1975] 2014 2016 2016 2017 2017 2017 2019 2019 2019 2019 2020 2021 2021 2022
[1989] 2022 2023 2023 2024 2024 2025 2025 2028 2030 2031 2033 2034 2034 2036
[2003] 2037 2038 2039 2041 2043 2044 2044 2044 2045 2048 2048 2049 2050 2050
[2017] 2051 2053 2057 2057 2058 2058 2059 2059 2059 2061 2063 2063 2067 2067
[2031] 2067 2068 2068 2069 2069 2069 2071 2071 2073 2076 2076 2076 2077 2078
[2045] 2078 2079 2080 2080 2080 2082 2084 2085 2085 2086 2087 2087 2087 2087
[2059] 2089 2090 2091 2091 2091 2092 2092 2093 2093 2094 2095 2096 2097 2099
[2073] 2102 2104 2105 2105 2105 2106 2106 2106 2107 2108 2108 2109 2109 2111
[2087] 2113 2114 2114 2114 2114 2115 2115 2116 2117 2117 2118 2118 2119 2120
[2101] 2120 2121 2124 2125 2130 2131 2134 2134 2135 2136 2136 2137 2139 2140
[2115] 2140 2141 2142 2142 2144 2144 2145 2145 2146 2148 2148 2148 2149 2149
[2129] 2149 2150 2151 2151 2152 2152 2152 2153 2153 2153 2154 2155 2156 2157
[2143] 2157 2157 2159 2159 2159 2160 2160 2161 2162 2162 2163 2165 2165 2169
[2157] 2170 2171 2171 2172 2173 2174 2175 2175 2176 2176 2177 2178 2179 2184
[2171] 2184 2185 2187 2188 2188 2188 2190 2192 2192 2193 2194 2194 2196 2197
[2185] 2199 2199 2199 2199 2200 2200 2201 2201 2203 2204 2204 2204 2207 2208
[2199] 2210 2211 2211 2212 2213 2214 2215 2215 2216 2218 2219 2221 2221 2221
[2213] 2222 2223 2223 2224 2224 2226 2226 2231 2233 2234 2235 2235 2236 2237
[2227] 2238 2238 2239 2239 2242 2243 2243 2244 2245 2246 2246 2247 2247 2248
[2241] 2249 2249 2250 2252 2252 2253 2254 2254 2254 2254 2256 2256 2257 2260
[2255] 2263 2263 2266 2267 2269 2271 2271 2273 2274 2275 2276 2277 2277 2277
[2269] 2278 2279 2280 2280 2280 2281 2281 2284 2284 2285 2286 2288 2289 2290
[2283] 2291 2291 2291 2292 2296 2297 2299 2299 2300 2301 2302 2303 2304 2304
[2297] 2305 2305 2309 2309 2309 2309 2310 2311 2311 2311 2311 2317 2318 2318
[2311] 2319 2320 2320 2320 2323 2325 2327 2327 2328 2329 2329 2331 2332 2332
[2325] 2332 2333 2335 2336 2337 2337 2338 2339 2339 2342 2342 2343 2346 2346
[2339] 2346 2350 2350 2351 2351 2354 2355 2359 2359 2360 2364 2365 2365 2365
[2353] 2365 2367 2368 2370 2372 2376 2378 2378 2379 2379 2381 2382 2382 2383
[2367] 2384 2385 2385 2386 2387 2388 2388 2389 2389 2391 2393 2393 2395 2396
[2381] 2398 2398 2399 2399 2399 2399 2399 2400 2403 2403 2405 2405 2405 2405
[2395] 2406 2406 2408 2408 2409 2409 2410 2411 2413 2414 2415 2417 2419 2421
[2409] 2428 2429 2433 2434 2437 2438 2439 2440 2443 2444 2445 2449 2449 2449
[2423] 2449 2450 2453 2454 2455 2456 2457 2458 2459 2459 2459 2459 2462 2465
[2437] 2466 2467 2467 2468 2469 2469 2470 2470 2473 2473 2474 2474 2475 2475
[2451] 2478 2478 2478 2481 2481 2482 2482 2484 2484 2486 2486 2488 2488 2490
[2465] 2491 2492 2494 2494 2495 2495 2496 2496 2497 2498 2499 2502 2503 2503
[2479] 2504 2506 2508 2508 2508 2509 2509 2510 2511 2512 2514 2514 2515 2516
[2493] 2518 2518 2518 2518 2518 2519 2519 2519 2521 2522 2523 2523 2523 2525
[2507] 2525 2527 2529 2530 2530 2531 2531 2531 2532 2539 2539 2539 2540 2541
[2521] 2542 2542 2542 2543 2547 2548 2548 2553 2553 2553 2553 2554 2556 2557
[2535] 2557 2557 2559 2561 2562 2563 2564 2564 2565 2565 2565 2566 2566 2567
[2549] 2568 2568 2569 2570 2571 2572 2574 2575 2579 2580 2581 2581 2581 2583
[2563] 2584 2584 2585 2585 2586 2588 2588 2589 2589 2589 2592 2592 2593 2595
[2577] 2595 2595 2596 2596 2597 2598 2598 2599 2600 2601 2602 2604 2604 2604
[2591] 2606 2607 2607 2608 2609 2610 2611 2611 2613 2613 2614 2614 2614 2614
[2605] 2614 2615 2618 2619 2621 2621 2622 2622 2623 2624 2624 2626 2628 2628
[2619] 2629 2629 2630 2630 2630 2631 2631 2631 2634 2635 2639 2640 2643 2644
[2633] 2644 2645 2646 2646 2647 2647 2648 2651 2651 2652 2658 2661 2662 2662
[2647] 2663 2664 2665 2667 2667 2667 2668 2669 2670 2671 2671 2673 2673 2673
[2661] 2673 2673 2674 2675 2676 2677 2678 2678 2679 2680 2680 2681 2681 2682
[2675] 2683 2683 2688 2688 2688 2689 2689 2692 2692 2692 2695 2695 2699 2699
[2689] 2699 2699 2702 2703 2704 2705 2706 2707 2708 2710 2712 2713 2713 2714
[2703] 2715 2717 2717 2718 2718 2718 2723 2724 2725 2725 2726 2727 2728 2728
[2717] 2729 2729 2729 2729 2731 2732 2732 2733 2733 2734 2735 2736 2737 2739
[2731] 2741 2741 2741 2744 2745 2745 2745 2749 2750 2750 2751 2752 2752 2752
[2745] 2752 2752 2753 2754 2754 2756 2758 2758 2759 2759 2760 2760 2760 2761
[2759] 2762 2763 2764 2765 2768 2769 2769 2771 2772 2773 2774 2774 2777 2777
[2773] 2779 2779 2780 2781 2782 2783 2784 2786 2786 2789 2789 2791 2791 2791
[2787] 2792 2794 2795 2801 2802 2803 2803 2803 2804 2804 2806 2807 2808 2808
[2801] 2809 2810 2811 2811 2811 2816 2817 2817 2819 2821 2822 2825 2827 2828
[2815] 2828 2830 2831 2833 2833 2833 2833 2834 2834 2834 2835 2836 2838 2838
[2829] 2839 2839 2839 2840 2841 2842 2842 2843 2843 2845 2846 2847 2847 2848
[2843] 2849 2850 2850 2851 2851 2852 2854 2854 2854 2856 2858 2859 2860 2861
[2857] 2861 2862 2864 2864 2864 2865 2865 2867 2867 2868 2868 2868 2869 2869
[2871] 2869 2870 2871 2871 2872 2874 2875 2876 2878 2881 2882 2884 2884 2885
[2885] 2885 2886 2887 2887 2889 2889 2889 2889 2890 2892 2892 2894 2895 2897
[2899] 2898 2898 2898 2899 2899 2901 2903 2903 2904 2904 2905 2906 2906 2906
[2913] 2908 2911 2911 2916 2917 2917 2918 2920 2920 2921 2922 2925 2925 2926
[2927] 2929 2930 2932 2932 2936 2940 2942 2942 2943 2944 2944 2945 2948 2949
[2941] 2949 2951 2951 2954 2955 2956 2956 2957 2958 2958 2959 2959 2960 2961
[2955] 2962 2962 2965 2966 2967 2968 2970 2973 2974 2974 2975 2975 2976 2976
[2969] 2976 2976 2977 2978 2979 2980 2980 2981 2981 2982 2983 2987 2988 2990
[2983] 2991 2992 2994 2995 2995 2995 2996 2997 2999 3002 3002 3003 3006 3008
[2997] 3009 3010 3011 3012 3013 3013 3014 3014 3015 3017 3019 3020 3020 3021
[3011] 3024 3025 3026 3027 3028 3029 3029 3030 3030 3033 3035 3036 3038 3039
[3025] 3041 3042 3042 3043 3043 3043 3044 3046 3046 3048 3051 3051 3054 3055
[3039] 3055 3055 3056 3057 3057 3057 3057 3061 3061 3062 3062 3065 3065 3065
[3053] 3067 3069 3069 3070 3071 3074 3074 3074 3075 3076 3078 3078 3079 3082
[3067] 3083 3084 3085 3088 3088 3088 3089 3089 3090 3092 3093 3094 3095 3096
[3081] 3098 3100 3100 3102 3104 3104 3104 3104 3105 3106 3107 3108 3109 3109
[3095] 3110 3110 3111 3112 3113 3113 3115 3116 3117 3119 3121 3121 3122 3123
[3109] 3123 3124 3124 3125 3125 3126 3127 3127 3128 3128 3129 3130 3132 3132
[3123] 3134 3136 3138 3142 3143 3143 3146 3147 3147 3148 3149 3149 3150 3150
[3137] 3152 3152 3156 3157 3157 3158 3161 3161 3162 3162 3163 3164 3165 3166
[3151] 3167 3167 3168 3169 3169 3169 3171 3173 3173 3174 3175 3178 3178 3179
[3165] 3179 3180 3181 3186 3187 3188 3189 3189 3190 3191 3193 3193 3194 3194
[3179] 3194 3194 3195 3195 3196 3196 3196 3196 3197 3200 3201 3201 3202 3202
[3193] 3203 3205 3206 3206 3206 3209 3209 3211 3211 3211 3212 3216 3217 3218
[3207] 3218 3220 3220 3221 3221 3222 3222 3223 3223 3223 3224 3224 3225 3226
[3221] 3227 3229 3230 3231 3234 3237 3239 3241 3241 3241 3242 3242 3242 3242
[3235] 3243 3244 3247 3249 3250 3250 3252 3253 3255 3256 3257 3258 3259 3260
[3249] 3261 3261 3261 3262 3262 3263 3263 3263 3263 3264 3267 3267 3268 3268
[3263] 3269 3269 3270 3270 3271 3273 3274 3278 3280 3280 3283 3284 3284 3285
[3277] 3285 3286 3286 3287 3288 3288 3288 3293 3295 3298 3301 3302 3303 3303
[3291] 3304 3304 3308 3308 3308 3310 3310 3310 3314 3314 3314 3318 3318 3319
[3305] 3319 3320 3320 3320 3321 3323 3325 3325 3327 3327 3330 3330 3333 3334
[3319] 3336 3336 3337 3337 3338 3339 3339 3342 3344 3345 3346 3347 3347 3347
[3333] 3350 3351 3351 3351 3351 3352 3352 3354 3356 3356 3357 3357 3359 3359
[3347] 3360 3361 3362 3363 3364 3364 3366 3367 3369 3369 3369 3370 3370 3370
[3361] 3370 3372 3372 3372 3372 3374 3375 3376 3376 3376 3376 3376 3378 3379
[3375] 3380 3380 3382 3384 3384 3387 3388 3388 3389 3390 3390 3390 3391 3391
[3389] 3392 3393 3394 3394 3394 3397 3397 3397 3397 3399 3400 3400 3402 3402
[3403] 3402 3405 3409 3412 3414 3415 3415 3415 3416 3416 3417 3418 3420 3420
[3417] 3420 3421 3422 3423 3424 3425 3427 3429 3435 3436 3437 3437 3437 3437
[3431] 3437 3439 3441 3443 3444 3444 3444 3444 3445 3445 3446 3447 3447 3447
[3445] 3447 3452 3452 3455 3455 3457 3458 3459 3459 3460 3462 3464 3469 3469
[3459] 3469 3469 3473 3473 3476 3478 3479 3481 3482 3482 3482 3483 3483 3484
[3473] 3485 3486 3487 3487 3490 3491 3492 3492 3494 3495 3497 3497 3498 3498
[3487] 3499 3499 3500 3500 3500 3501 3501 3502 3503 3503 3504 3504 3505 3506
[3501] 3507 3507 3508 3510 3510 3514 3515 3516 3516 3518 3518 3518 3521 3523
[3515] 3526 3527 3528 3529 3530 3531 3531 3532 3532 3532 3533 3535 3535 3539
[3529] 3540 3541 3542 3542 3543 3545 3545 3546 3546 3546 3547 3548 3548 3549
[3543] 3549 3550 3551 3552 3552 3552 3554 3555 3557 3557 3560 3561 3561 3561
[3557] 3562 3563 3563 3568 3571 3573 3574 3574 3574 3576 3577 3578 3579 3581
[3571] 3583 3584 3586 3587 3587 3587 3587 3587 3588 3589 3589 3590 3591 3591
[3585] 3592 3594 3595 3596 3596 3597 3599 3600 3600 3600 3602 3604 3604 3604
[3599] 3604 3606 3607 3607 3608 3609 3611 3613 3613 3615 3615 3617 3619 3620
[3613] 3620 3622 3623 3624 3624 3625 3625 3625 3627 3631 3632 3634 3635 3636
[3627] 3636 3639 3640 3640 3641 3642 3642 3643 3643 3643 3643 3644 3644 3646
[3641] 3648 3649 3649 3650 3651 3652 3654 3654 3656 3657 3659 3660 3660 3661
[3655] 3662 3663 3663 3665 3665 3667 3668 3669 3669 3670 3670 3671 3672 3673
[3669] 3673 3675 3676 3676 3677 3677 3678 3678 3679 3681 3681 3683 3685 3688
[3683] 3689 3691 3692 3693 3694 3695 3696 3699 3700 3700 3701 3702 3704 3705
[3697] 3706 3706 3708 3708 3709 3712 3713 3714 3716 3717 3717 3717 3718 3719
[3711] 3719 3720 3720 3721 3721 3722 3722 3723 3724 3724 3725 3725 3726 3727
[3725] 3728 3728 3730 3730 3731 3731 3732 3735 3736 3736 3737 3739 3739 3739
[3739] 3739 3740 3741 3741 3742 3746 3746 3748 3749 3750 3750 3751 3753 3753
[3753] 3754 3755 3755 3755 3757 3759 3759 3760 3761 3762 3762 3763 3766 3767
[3767] 3767 3768 3768 3769 3769 3769 3770 3771 3771 3771 3771 3771 3775 3775
[3781] 3776 3777 3777 3780 3782 3787 3788 3790 3792 3795 3795 3796 3796 3798
[3795] 3799 3800 3801 3802 3803 3804 3804 3805 3807 3808 3809 3809 3809 3810
[3809] 3812 3812 3813 3813 3813 3814 3814 3815 3816 3817 3818 3819 3819 3819
[3823] 3821 3821 3823 3831 3833 3835 3836 3837 3839 3839 3839 3840 3841 3841
[3837] 3841 3842 3846 3846 3846 3850 3851 3853 3854 3855 3855 3855 3856 3857
[3851] 3858 3859 3859 3860 3861 3862 3863 3863 3863 3864 3866 3866 3868 3868
[3865] 3868 3869 3869 3870 3871 3871 3872 3873 3873 3874 3875 3875 3876 3877
[3879] 3877 3879 3880 3880 3880 3881 3881 3882 3883 3884 3884 3885 3885 3885
[3893] 3887 3887 3888 3889 3889 3889 3890 3890 3891 3892 3892 3892 3892 3894
[3907] 3894 3895 3895 3895 3897 3898 3899 3899 3900 3901 3902 3902 3902 3904
[3921] 3906 3908 3912 3914 3914 3915 3917 3917 3917 3921 3921 3921 3921 3923
[3935] 3924 3925 3926 3926 3926 3928 3929 3930 3932 3932 3933 3935 3938 3938
[3949] 3939 3941 3942 3942 3942 3942 3943 3945 3946 3947 3951 3954 3956 3956
[3963] 3956 3957 3963 3963 3964 3964 3964 3965 3966 3971 3973 3973 3974 3976
[3977] 3977 3979 3979 3980 3980 3980 3981 3982 3982 3982 3982 3983 3985 3985
[3991] 3987 3988 3989 3989 3989 3989 3990 3990 3992 3994 3997 3998 3998 3999
[4005] 4000 4001 4001 4003 4004 4006 4009 4009 4011 4011 4012 4012 4014 4014
[4019] 4015 4016 4016 4018 4018 4019 4020 4023 4024 4024 4026 4027 4029 4030
[4033] 4031 4032 4033 4034 4034 4036 4037 4037 4038 4039 4040 4045 4046 4046
[4047] 4047 4047 4052 4053 4054 4054 4055 4057 4058 4058 4058 4059 4059 4062
[4061] 4062 4062 4064 4064 4065 4065 4065 4065 4066 4068 4069 4073 4074 4075
[4075] 4075 4076 4077 4077 4079 4080 4080 4081 4082 4082 4083 4084 4086 4090
[4089] 4091 4091 4091 4092 4092 4092 4092 4093 4094 4095 4095 4097 4099 4099
[4103] 4101 4101 4101 4101 4103 4104 4106 4107 4108 4110 4110 4110 4111 4112
[4117] 4112 4113 4114 4114 4116 4116 4117 4117 4118 4119 4119 4121 4123 4123
[4131] 4124 4125 4125 4131 4131 4131 4133 4138 4142 4143 4144 4144 4145 4145
[4145] 4147 4148 4149 4150 4151 4151 4152 4152 4153

Again, it creates a list of indices. The first element of the list, index_boot[[1]], contains the row indices that will be in the training set. Note that, it is of length 4,153. In other words, the training set during this first replicate is of the same dimension as the whole training set df_tr. Note also that, in index_boot[[1]], there are indices that are replicated. This is the bootstrap sampling process. Some rows will be replicated in the training set. This also means that some rows of df_tr will not be in index_boot[[1]]. These rows are said to be out-of-bag and form the validation set. See below the dimensions of the data frames.

df_boot_tr <- df_tr[index_boot[[1]],]
dim(df_boot_tr)
df_boot_val <- df_tr[-index_boot[[1]],]
dim(df_boot_val)
[1] 4153   12
[1] 1516   12

We now fit the data to this first sample training set.

Doc_boot <- glm(visits~., data=df_boot_tr, family="binomial") %>% step()
Start:  AIC=3733.25
visits ~ gender + age + income + illness + reduced + health + 
    private + freepoor + freerepat + nchronic + lchronic

            Df Deviance    AIC
- gender     1   3710.4 3732.4
- nchronic   1   3711.1 3733.1
<none>           3709.2 3733.2
- freepoor   1   3711.7 3733.7
- freerepat  1   3713.2 3735.2
- income     1   3716.4 3738.4
- health     1   3716.5 3738.5
- age        1   3719.9 3741.9
- private    1   3722.7 3744.7
- lchronic   1   3725.1 3747.1
- illness    1   3776.4 3798.4
- reduced    1   3789.8 3811.8

Step:  AIC=3732.4
visits ~ age + income + illness + reduced + health + private + 
    freepoor + freerepat + nchronic + lchronic

            Df Deviance    AIC
<none>           3710.4 3732.4
- nchronic   1   3712.6 3732.6
- freepoor   1   3712.9 3732.9
- freerepat  1   3714.7 3734.7
- health     1   3718.0 3738.0
- income     1   3718.8 3738.8
- age        1   3722.0 3742.0
- private    1   3725.0 3745.0
- lchronic   1   3726.2 3746.2
- illness    1   3778.3 3798.3
- reduced    1   3791.2 3811.2

The accuracy is then computed with the 632-rule: first, the apparent accuracy is computed (accuracy on the sample training set), then the out-of-bag accuracy (the accuracy on the validation set), then the final accuracy estimate is the 0.368/0.632-combination of the two.

Doc_boot_prob_val <- predict(Doc_boot, newdata=df_boot_val, type="response")
Doc_boot_pred_val <- ifelse(Doc_boot_prob_val>0.5,"Yes","No")
oob_acc <- confusionMatrix(data=as.factor(Doc_boot_pred_val), reference = df_boot_val$visits)$overall[1]

Doc_boot_prob_tr <- predict(Doc_boot, newdata=df_boot_tr, type="response")
Doc_boot_pred_tr <- ifelse(Doc_boot_prob_tr>0.5,"Yes","No")
app_acc <- confusionMatrix(data=as.factor(Doc_boot_pred_tr), reference = df_boot_tr$visits)$overall[1]

oob_acc ## out-of-bag accuracy
app_acc ## apparent accuracy
0.368*app_acc + 0.632*oob_acc ## accuracy estimate
 Accuracy 
0.8120053 
 Accuracy 
0.8025524 
 Accuracy 
0.8085266 

First, we create the replicates using the resample function from sklearn.utils. Please note that unlike caret::createResample(), in sklearn (to the best of our knowledge), there’s no method that returns a list of the samples, so with resample, we get one set of resampled data points. This doesn’t matter for now, but in the following sub-section, we will write a function to do the same thing in python.

from sklearn.utils import resample

np.random.seed(897)
df_boot_tr = resample(r.df_tr, n_samples=len(r.df_tr), random_state=897)

The resample function returns a new data frames with the same number of samples as the original r.df_tr, but some rows will be replicated. This also means that some rows of r.df_tr will not be in the bootstrapped data frames These rows are said to be out-of-bag and form the validation set. See below the dimensions of the data frames.

df_boot_tr.shape
oob_mask = ~r.df_tr.index.isin(df_boot_tr.index.values)
df_boot_val = r.df_tr[oob_mask]
df_boot_val.shape
(4153, 12)
(1524, 12)

There’s a difference between the shape of df_boot_val because of the difference in random generators between R & python. If you change the number for the random generator in python (i.e., np.random.seed(897)) or in R (i.e., set.seed(897)), you’ll see that the results will be slightly different.

Loop on the 100 sample

The previous code is looped. The accuracy measures are stored in vectors. The code can be quite long to run.

oob_acc_vec <- numeric(100)
app_acc_vec <- numeric(100)
acc_vec <- numeric(100)
for (i in 1:100){
  df_boot_tr <- df_tr[index_boot[[i]],]
  df_boot_val <- df_tr[-index_boot[[i]],]
  
  Doc_boot <- glm(visits~., data=df_boot_tr, family="binomial") %>% step(trace=0)
  Doc_boot_prob_val <- predict(Doc_boot, newdata=df_boot_val, type="response")
  Doc_boot_pred_val <- ifelse(Doc_boot_prob_val>0.5,"Yes","No")
  oob_acc_vec[i] <- confusionMatrix(data=as.factor(Doc_boot_pred_val), reference = df_boot_val$visits)$overall[1]
  
  Doc_boot_prob_tr <- predict(Doc_boot, newdata=df_boot_tr, type="response")
  Doc_boot_pred_tr <- ifelse(Doc_boot_prob_tr>0.5,"Yes","No")
  app_acc_vec[i] <- confusionMatrix(data=as.factor(Doc_boot_pred_tr), reference = df_boot_tr$visits)$overall[1]
  
  acc_vec[i] <- 0.368*app_acc_vec[i] + 0.632*oob_acc_vec[i]
}

acc_vec
  [1] 0.8085266 0.8030856 0.7998945 0.8094963 0.8070382 0.8066690 0.8159138
  [8] 0.8055696 0.8048381 0.8069395 0.8083230 0.8085707 0.8125019 0.8091844
 [15] 0.8131225 0.8029512 0.8148320 0.8127014 0.8076272 0.8128124 0.8089242
 [22] 0.8095967 0.8073836 0.8094355 0.8057663 0.8040773 0.8057475 0.8024387
 [29] 0.8099869 0.8046851 0.8099349 0.8091306 0.8076273 0.8100650 0.8122369
 [36] 0.8126430 0.7987802 0.8016194 0.8101302 0.8079831 0.8094068 0.8110767
 [43] 0.8060283 0.8135686 0.8035090 0.8042121 0.8082690 0.8111320 0.8118860
 [50] 0.8065804 0.8119387 0.8105766 0.8076084 0.8020889 0.8084271 0.8039827
 [57] 0.8013010 0.8067970 0.8074908 0.8040691 0.8098879 0.8075923 0.8087700
 [64] 0.8145400 0.8152086 0.8138747 0.8100496 0.8068013 0.8034611 0.8013294
 [71] 0.8127765 0.8205267 0.8139015 0.8115502 0.8061950 0.8110738 0.8061456
 [78] 0.8151054 0.8019486 0.8107303 0.8053233 0.8068712 0.8099626 0.8071558
 [85] 0.8079275 0.8069616 0.8141566 0.8070813 0.8074818 0.8156978 0.8073322
 [92] 0.8044596 0.8075325 0.8115116 0.8098947 0.8089585 0.8043670 0.8107245
 [99] 0.8162958 0.8062559

Like for the CV, we can estimate the expected accuracy and its dispersion.

mean(acc_vec)
sd(acc_vec)
[1] 0.8084616
[1] 0.004015357

In this part of the code, we perform the bootstrap procedure with 100 samples. To that, we will implement our own function to create the index n-times for a given dataset. This ensures that we get a similar output to caret::createResample(). In this case, we apply this function to our main training dataframe 100 times.

def create_resample(data, times=100, random_seed=None):
    # If you're not familiar with the documentation below, they are called
    # `docstrings` and whenever you ask help for a function or see it's documentation,
    # they are generated from that
    """
    Generate bootstrap sample indices for data.
    
    Args:
    - data (array-like): The data to bootstrap.
    - times (int): The number of bootstrap samples to generate.
    - random_seed (int): The random seed to use for reproducibility.
    
    Returns:
    - samples (list of arrays): A list of times bootstrap sample indices.
    """
    np.random.seed(random_seed)
    n_samples = len(data)
    samples = []
    for _ in range(times):
        indices = np.random.choice(n_samples, n_samples, replace=True)
        samples.append(indices)
    return samples

# apply the new created function
index_boot = create_resample(r.df_tr, times=100, random_seed = 123)
# we can see if we successfully replicated the sampling process 100 times
print(len(index_boot))
# check if we have the correct number of rows (e.g. for the first element)
print(len(index_boot[0]))
# alternatively to see this information, you can uncomment & run the code below
# np.asarray(index_boot).shape
100
4153
Note

One thing to note is that we could have used the sklearn.utils.resample introduced earlier to directly get a list of dataframes with the randomly chosen indices. The issue here would be rather a computational one, as we have to extract the rows many times from the dataset and then hold all this data in memory, which is redundant. So although this may not be a problem for 100 replications, it can quickly start to become an issue if you want to replicated many more times (e.g., 100,000 times). The best approach is to get the indices, and then subset the rows only when needed.

import numpy as np
from sklearn.utils import resample

def create_n_resamples(data, times, random_seed=None):
    """
    Generate n_bootstraps bootstrap samples of data.
    
    Args:
    - data (array-like): The data to bootstrap.
    - n_bootstraps (int): The number of bootstrap samples to generate.
    - random_seed (int): The random seed to use for reproducibility.
    
    Returns:
    - bootstrap_samples (list of lists): A list of n_bootstraps bootstrap samples.
    """
    np.random.seed(random_seed)
    bootstrap_samples = []
    for i in range(times):
        sample = resample(data)
        bootstrap_samples.append(sample)
    return bootstrap_samples

dfs_boot = create_n_resamples(r.df_tr, times=100, random_seed = 123) 

For each sample, we calculate the out-of-bag accuracy, the apparent accuracy, and the final accuracy estimate using the 0.368/0.632 rule. This is done using a loop that iterates 100 times, once for each bootstrap sample. The steps that the code follows are similar to R, and are outlined below:

  1. We set up three arrays to store the out-of-bag accuracy, the apparent accuracy, and the final accuracy estimate for each of the 100 bootstrap samples.
  2. In the loop, we perform the following steps for each bootstrap sample:
    1. Use the generate a random list of indices with replacement, which forms the bootstrap training set.
    2. Create a mask to extract the out-of-bag (validation) set from the original training set.
    3. Train the logistic regression model with RFE on the bootstrap training set.
    4. Compute the out-of-bag accuracy by predicting on the validation set and comparing the predicted labels to the true labels.
    5. Compute the apparent accuracy by predicting on the bootstrap training set and comparing the predicted labels to the true labels.
    6. Calculate the final accuracy estimate for the current bootstrap sample using the 0.368/0.632 rule.
  3. Once the loop is complete, the acc_vec array will contain the final accuracy estimates for all 100 bootstrap samples. We can then calculate the mean and standard deviation of these accuracy estimates to get an overall understanding of the model’s performance.
# we one-hote encode the categorical variables
## notice that we didn't use the argument `drop_first` before, since this is like
## making dummy variable m - 1 where m is the number of variables you have
r.df_tr_encoded = pd.get_dummies(r.df_tr, drop_first=True)

oob_acc_vec = np.zeros(100)
app_acc_vec = np.zeros(100)
acc_vec = np.zeros(100)

for i in range(100):
    df_boot_tr = r.df_tr_encoded.iloc[index_boot[i]]
    y_boot_tr = df_boot_tr["visits_Yes"].astype(int)
    X_boot_tr = df_boot_tr.drop("visits_Yes", axis=1)

    oob_mask = ~r.df_tr_encoded.index.isin(df_boot_tr.index.values)
    df_boot_val = r.df_tr_encoded[oob_mask]
    y_boot_val = df_boot_val["visits_Yes"].astype(int)
    X_boot_val = df_boot_val.drop("visits_Yes", axis=1)

    model = LogisticRegression(solver='liblinear')
    rfe = RFE(model)
    rfe.fit(X_boot_tr, y_boot_tr);

    pred_probs_val = rfe.predict_proba(X_boot_val)[:, 1]
    Doc_boot_pred_val = (pred_probs_val > 0.5).astype(int)
    oob_acc = accuracy_score(y_boot_val, Doc_boot_pred_val)
    oob_acc_vec[i] = oob_acc

    pred_probs_tr = rfe.predict_proba(X_boot_tr)[:, 1]
    Doc_boot_pred_tr = (pred_probs_tr > 0.5).astype(int)
    app_acc = accuracy_score(y_boot_tr, Doc_boot_pred_tr)
    app_acc_vec[i] = app_acc

    acc_vec[i] = 0.368 * app_acc + 0.632 * oob_acc

print(acc_vec)
RFE(estimator=LogisticRegression(solver='liblinear'))
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
[0.79164683 0.79616144 0.79364513 0.78670504 0.7986946  0.79868972
 0.79161246 0.7965414  0.80202118 0.79994412 0.78606506 0.79846614
 0.78894153 0.79368873 0.79046191 0.79501138 0.79628018 0.80036159
 0.79429755 0.79338894 0.78586846 0.79973575 0.79466775 0.79211937
 0.80096923 0.79428578 0.7933537  0.79342414 0.80267463 0.79866942
 0.79084131 0.7937733  0.79711103 0.79320698 0.78894039 0.79328919
 0.79961158 0.80009905 0.787486   0.79245629 0.79372317 0.80025018
 0.79695854 0.79163329 0.7848291  0.79522696 0.7965682  0.80253766
 0.79527551 0.79328691 0.79340388 0.79624061 0.79219718 0.79049386
 0.79403538 0.79808693 0.79664166 0.79799292 0.80114515 0.80303275
 0.79363897 0.79560436 0.79695715 0.79222779 0.7934067  0.79406251
 0.79455184 0.78963621 0.79352221 0.79564139 0.7983747  0.78908189
 0.79001833 0.79233528 0.79785744 0.79740789 0.79438725 0.79769307
 0.7903751  0.7916545  0.79395087 0.79706869 0.79963773 0.79651521
 0.79497189 0.79226763 0.79372328 0.78538195 0.7984487  0.79944822
 0.79073859 0.79801992 0.79788277 0.80019645 0.79505795 0.79504863
 0.78860757 0.80911356 0.79560276 0.79835708]

Automated approach

We only need to change the method in the trainControl function. The corresponding method is “boot632”.

set.seed(346)
trctrl <- trainControl(method = "boot632", number=100)
Doc_boot <- train(visits ~., data = df_tr, method = "glmStepAIC", family="binomial",
                   trControl=trctrl, trace = 0)
Doc_boot
Generalized Linear Model with Stepwise Feature Selection 

4153 samples
  11 predictor
   2 classes: 'No', 'Yes' 

No pre-processing
Resampling: Bootstrapped (100 reps) 
Summary of sample sizes: 4153, 4153, 4153, 4153, 4153, 4153, ... 
Resampling results:

  Accuracy   Kappa    
  0.8091758  0.1947029

As sklearn does not offer bootstrap with the 0.632 rule, we use bootstrap_point632_score function from the mlxtend library to perform bootstrapping with the 0.632 rule for our Logistic Regression model. We will use mlxtend with R for bootstrapping with the 0.632 rule.

Please note for this part, we don’t make any step-wise feature selection here as in the case of caret (i.e., glmStepAIC), but similar feature selections such as sklearn.feature_selection.RFE can be implemented since, as mentioned in the Ex_ML_LinLogReg exercises, there are no exact implementations of step-wise AIC regression with the libraries of interest in python.

from mlxtend.evaluate import bootstrap_point632_score

np.random.seed(346)

# Fit the logistic regression model
model = LogisticRegression(solver='liblinear')

# Compute bootstrap point 632 scores
scores = bootstrap_point632_score(estimator=model, X=X_train, y=y_train, n_splits=100, random_seed=123)

# Print the mean accuracy and standard deviation
print("Mean accuracy:", np.mean(scores))
print("Standard deviation:", np.std(scores))
Mean accuracy: 0.8080373363530166
Standard deviation: 0.005025205465388738

The results are now very close to our model in caret.

Balancing data

In this part, we apply the balancing data technique in order to improve the prediction of “yes” with the doctor visit data. The table below reveals the unbalance problem.

## Statistics on the training set
table(df_tr$visits)

  No  Yes 
3313  840 

Since there are many more “No” than “Yes”, any model favors the prediction of the “No”. It results a good accuracy but the specificity (or the sensitivity depending on the choice of the positive class) is low, as well as the balanced accuracy.

Doc_lr <- glm(visits~., data=df_tr, family="binomial") %>% step(trace=0)
Doc_lr_prob <- predict(Doc_lr, newdata=df_te, type="response")
Doc_lr_pred <- ifelse(Doc_lr_prob>0.5,"Yes","No")
confusionMatrix(data=as.factor(Doc_lr_pred), reference = df_te$visits)
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  809 179
       Yes  19  30
                                          
               Accuracy : 0.8091          
                 95% CI : (0.7838, 0.8326)
    No Information Rate : 0.7985          
    P-Value [Acc > NIR] : 0.2089          
                                          
                  Kappa : 0.1689          
                                          
 Mcnemar's Test P-Value : <2e-16          
                                          
            Sensitivity : 0.9771          
            Specificity : 0.1435          
         Pos Pred Value : 0.8188          
         Neg Pred Value : 0.6122          
             Prevalence : 0.7985          
         Detection Rate : 0.7801          
   Detection Prevalence : 0.9527          
      Balanced Accuracy : 0.5603          
                                          
       'Positive' Class : No              
                                          
r.df_tr['visits'].value_counts()
visits
No     3313
Yes     840
Name: count, dtype: int64
lr = LogisticRegression(solver='liblinear')
lr.fit(X_train, y_train);
lr_pred = lr.predict(X_test)
lr_cf = confusion_matrix(y_test, lr_pred)
print(lr_cf)
[[809  19]
 [179  30]]

To calculate all the other scores aside from the confusion matrix, we actually have to compute them manually:

from sklearn.metrics import balanced_accuracy_score, recall_score

tn, fp, fn, tp = lr_cf.ravel()

specificity = tn / (tn + fp)
sensitivity = recall_score(y_test, lr_pred, pos_label='Yes')
balanced_acc = balanced_accuracy_score(y_test, lr_pred)
accuracy = accuracy_score(y_test, lr_pred)

print(f"Accuracy: {accuracy:.3f}")
print(f"Balanced Accuracy: {balanced_acc:.3f}")
print(f"Specificity: {specificity:.3f}")
print(f"Sensitivity: {sensitivity:.3f}")
Accuracy: 0.809
Balanced Accuracy: 0.560
Specificity: 0.977
Sensitivity: 0.144

Please note that Specificity and Sensitivity have the reverse values compared to R, and that’s because the confusion matrix in R first takes the predicted values and then the true values. In contrast, it is the confusion matrix from sklearn, the true values are given before the predicted ones. The interpretation does not change, and it’s only about which class you consider as your positive class.

Sub-sampling

Balancing using sub-sampling consists of taking all the cases in the smallest class (i.e., Yes) and extract at random the same amount of cases in the largest category (i.e., No).

n_yes <- min(table(df_tr$visits)) ## 840

df_tr_no <- filter(df_tr, visits=="No") ## the "No" cases
df_tr_yes <- filter(df_tr, visits=="Yes") ## The "Yes" cases

index_no <- sample(size=n_yes, x=1:nrow(df_tr_no), replace=FALSE) ## sub-sample 840 instances from the "No"

df_tr_subs <- data.frame(rbind(df_tr_yes, df_tr_no[index_no,])) ## Bind all the "Yes" and the sub-sampled "No"
table(df_tr_subs$visits) ## The cases are balanced

 No Yes 
840 840 

Now let us see the result on the accuracy measures.

Doc_lr_subs <- glm(visits~., data=df_tr_subs, family="binomial") %>% step(trace=0)
Doc_lr_subs_prob <- predict(Doc_lr_subs, newdata=df_te, type="response")
Doc_lr_subs_pred <- ifelse(Doc_lr_subs_prob>0.5,"Yes","No")
confusionMatrix(data=as.factor(Doc_lr_subs_pred), reference = df_te$visits)
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  598  86
       Yes 230 123
                                          
               Accuracy : 0.6953          
                 95% CI : (0.6663, 0.7232)
    No Information Rate : 0.7985          
    P-Value [Acc > NIR] : 1               
                                          
                  Kappa : 0.2471          
                                          
 Mcnemar's Test P-Value : 8.668e-16       
                                          
            Sensitivity : 0.7222          
            Specificity : 0.5885          
         Pos Pred Value : 0.8743          
         Neg Pred Value : 0.3484          
             Prevalence : 0.7985          
         Detection Rate : 0.5767          
   Detection Prevalence : 0.6596          
      Balanced Accuracy : 0.6554          
                                          
       'Positive' Class : No              
                                          
n_yes = min(r.df_tr['visits'].value_counts()) ## 840

df_tr_no = r.df_tr[r.df_tr['visits'] == "No"] ## the "No" cases
df_tr_yes = r.df_tr[r.df_tr['visits'] == "Yes"] ## The "Yes" cases

index_no = np.random.choice(df_tr_no.index, size=n_yes, replace=False)

df_tr_subs = pd.concat([df_tr_yes, df_tr_no.loc[index_no]])
df_tr_subs['visits'].value_counts() ## The cases like R are balanced
visits
No     840
Yes    840
Name: count, dtype: int64

Now to the calculating the scores again:

X_train_subs = pd.get_dummies(df_tr_subs.drop(columns=['visits']))
y_train_subs = df_tr_subs['visits']

lr_subs = LogisticRegression(solver='liblinear')
lr_subs.fit(X_train_subs, y_train_subs);
lr_subs_pred = lr_subs.predict(X_test)
lr_subs_cf = confusion_matrix(y_test, lr_subs_pred)

tn_subs, fp_subs, fn_subs, tp_subs = lr_subs_cf.ravel()

specificity_subs = tn_subs / (tn_subs + fp_subs)
sensitivity_subs = recall_score(y_test, lr_subs_pred, pos_label='Yes')
balanced_acc_subs = balanced_accuracy_score(y_test, lr_subs_pred)
accuracy_subs = accuracy_score(y_test, lr_subs_pred)

print(lr_subs_cf)
print(f"Accuracy: {accuracy_subs:.3f}")
print(f"Balanced Accuracy: {balanced_acc_subs:.3f}")
print(f"Specificity: {specificity_subs:.3f}")
print(f"Sensitivity: {sensitivity_subs:.3f}")
[[615 213]
 [ 89 120]]
Accuracy: 0.709
Balanced Accuracy: 0.658
Specificity: 0.743
Sensitivity: 0.574

Same conclusion as R (albeit with slightly different values).

As expected, the accuracy has decreased but the balanced accuracy has increased. Depending on the aim of the prediction, this model may be much better to use than the one trained on the unbalanced data.

Resampling

Balancing by resampling follows the same aim. The difference with sub-sampling is that the resampling increases the number of cases in the smallest class by resampling at random from them. The codes below are explicit:

n_no <- max(table(df_tr$visits)) ## 3313

df_tr_no <- filter(df_tr, visits=="No")
df_tr_yes <- filter(df_tr, visits=="Yes")

index_yes <- sample(size=n_no, x=1:nrow(df_tr_yes), replace=TRUE)
df_tr_res <- data.frame(rbind(df_tr_no, df_tr_yes[index_yes,]))
table(df_tr_res$visits)

  No  Yes 
3313 3313 

Now, we have a balanced data set where each class has the same amount as the largest class (i.e., “No”) in the original training set. The effect on the model fit is very similar to the subsampling:

Doc_lr_res <- glm(visits~., data=df_tr_res, family="binomial") %>% step(trace=0)
Doc_lr_res_prob <- predict(Doc_lr_res, newdata=df_te, type="response")
Doc_lr_res_pred <- ifelse(Doc_lr_res_prob>0.5,"Yes","No")
confusionMatrix(data=as.factor(Doc_lr_res_pred), reference = df_te$visits)
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  611  90
       Yes 217 119
                                          
               Accuracy : 0.704           
                 95% CI : (0.6751, 0.7316)
    No Information Rate : 0.7985          
    P-Value [Acc > NIR] : 1               
                                          
                  Kappa : 0.2504          
                                          
 Mcnemar's Test P-Value : 6.422e-13       
                                          
            Sensitivity : 0.7379          
            Specificity : 0.5694          
         Pos Pred Value : 0.8716          
         Neg Pred Value : 0.3542          
             Prevalence : 0.7985          
         Detection Rate : 0.5892          
   Detection Prevalence : 0.6760          
      Balanced Accuracy : 0.6537          
                                          
       'Positive' Class : No              
                                          
n_no = max(r.df_tr['visits'].value_counts()) ## 3313

df_tr_no = r.df_tr[r.df_tr['visits'] == "No"]
df_tr_yes = r.df_tr[r.df_tr['visits'] == "Yes"]

index_yes = np.random.choice(df_tr_yes.index, size=n_no, replace=True)
df_tr_res = pd.concat([df_tr_no, df_tr_yes.loc[index_yes]])
df_tr_res['visits'].value_counts()
visits
No     3313
Yes    3313
Name: count, dtype: int64

Now we can model again with the resampled data

X_train_res = pd.get_dummies(df_tr_res.drop(columns=['visits']))
y_train_res = df_tr_res['visits']

lr_res = LogisticRegression(solver='liblinear')
lr_res.fit(X_train_res, y_train_res);
lr_res_pred = lr_res.predict(X_test)

lr_res_cf = confusion_matrix(y_test, lr_res_pred)

tn_res, fp_res, fn_res, tp_res = lr_res_cf.ravel()

specificity_res = tn_res / (tn_res + fp_res)
sensitivity_res = recall_score(y_test, lr_res_pred, pos_label='Yes')
balanced_acc_res = balanced_accuracy_score(y_test, lr_res_pred)
accuracy_res = accuracy_score(y_test, lr_res_pred)

print(lr_res_cf)
print(f"Accuracy: {accuracy_res:.3f}")
print(f"Balanced Accuracy: {balanced_acc_res:.3f}")
print(f"Specificity: {specificity_res:.3f}")
print(f"Sensitivity: {sensitivity_res:.3f}")
[[606 222]
 [ 84 125]]
Accuracy: 0.705
Balanced Accuracy: 0.665
Specificity: 0.732
Sensitivity: 0.598

Whether one should prefer sub-sampling or resampling depends on the amount and the richness of the data.

Your turn

Repeat the analysis on the German credit data. Balance the data using either method. Then, using caret (R) or sklearn (python) and either CV or Bootstrap, put several models in competition. Select the best one according to your choice of score. Finally, use the test set to see if the best model does not overfit the training set.

Doing this will have achieved a complete supervised learning task from A to Z.