Machine Learning Workflow: MLP (Heart Data)

Biostat 203B

Author

Dr. Hua Zhou @ UCLA

Published

March 12, 2023

Display system information for reproducibility.

sessionInfo()
R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.2.1

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] compiler_4.2.2  fastmap_1.1.1   cli_3.6.0       tools_4.2.2    
 [5] htmltools_0.5.4 rstudioapi_0.14 yaml_2.3.7      rmarkdown_2.20 
 [9] knitr_1.42      xfun_0.37       digest_0.6.31   jsonlite_1.8.4 
[13] rlang_1.0.6     evaluate_0.20  
import IPython
print(IPython.sys_info())
{'commit_hash': '15ea1ed5a',
 'commit_source': 'installation',
 'default_encoding': 'utf-8',
 'ipython_path': '/Applications/miniconda3/lib/python3.10/site-packages/IPython',
 'ipython_version': '8.10.0',
 'os_name': 'posix',
 'platform': 'macOS-13.2.1-arm64-arm-64bit',
 'sys_executable': '/usr/local/bin/python3',
 'sys_platform': 'darwin',
 'sys_version': '3.10.9 (main, Jan 11 2023, 09:20:18) [Clang 14.0.6 ]'}

1 Overview

We illustrate the typical machine learning workflow for multi-layer perceptron (MLP) using the Heart data set. The outcome is AHD (Yes or No).

  1. Initial splitting to test and non-test sets.

  2. Pre-processing of data: dummy coding categorical variables, standardizing numerical variables, imputing missing values, …

  3. Tune the MLP algorithm using 5-fold cross-validation (CV) on the non-test data.

  4. Choose the best model by CV and refit it on the whole non-test data.

  5. Final classification on the test data.

2 Heart data

The goal is to predict the binary outcome AHD (Yes or No) of patients.

# Load libraries
library(GGally)
library(gtsummary)
library(keras)
library(tidyverse)
library(tidymodels)

# Load the `Heart.csv` data.
Heart <- read_csv("Heart.csv") %>% 
  # first column is patient ID, which we don't need
  select(-1) %>%
  # RestECG is categorical with value 0, 1, 2
  mutate(RestECG = as.character(RestECG)) %>%
  print(width = Inf)
# A tibble: 303 × 14
     Age   Sex ChestPain    RestBP  Chol   Fbs RestECG MaxHR ExAng Oldpeak Slope
   <dbl> <dbl> <chr>         <dbl> <dbl> <dbl> <chr>   <dbl> <dbl>   <dbl> <dbl>
 1    63     1 typical         145   233     1 2         150     0     2.3     3
 2    67     1 asymptomatic    160   286     0 2         108     1     1.5     2
 3    67     1 asymptomatic    120   229     0 2         129     1     2.6     2
 4    37     1 nonanginal      130   250     0 0         187     0     3.5     3
 5    41     0 nontypical      130   204     0 2         172     0     1.4     1
 6    56     1 nontypical      120   236     0 0         178     0     0.8     1
 7    62     0 asymptomatic    140   268     0 2         160     0     3.6     3
 8    57     0 asymptomatic    120   354     0 0         163     1     0.6     1
 9    63     1 asymptomatic    130   254     0 2         147     0     1.4     2
10    53     1 asymptomatic    140   203     1 2         155     1     3.1     3
      Ca Thal       AHD  
   <dbl> <chr>      <chr>
 1     0 fixed      No   
 2     3 normal     Yes  
 3     2 reversable Yes  
 4     0 normal     No   
 5     0 normal     No   
 6     0 normal     No   
 7     2 normal     Yes  
 8     0 normal     No   
 9     1 reversable Yes  
10     0 reversable Yes  
# … with 293 more rows
# Numerical summaries stratified by the outcome `AHD`.
Heart %>% tbl_summary(by = AHD)
Characteristic No, N = 1641 Yes, N = 1391
Age 52 (45, 59) 58 (52, 62)
Sex 92 (56%) 114 (82%)
ChestPain
    asymptomatic 39 (24%) 105 (76%)
    nonanginal 68 (41%) 18 (13%)
    nontypical 41 (25%) 9 (6.5%)
    typical 16 (9.8%) 7 (5.0%)
RestBP 130 (120, 140) 130 (120, 145)
Chol 234 (209, 267) 249 (218, 284)
Fbs 23 (14%) 22 (16%)
RestECG
    0 95 (58%) 56 (40%)
    1 1 (0.6%) 3 (2.2%)
    2 68 (41%) 80 (58%)
MaxHR 161 (149, 172) 142 (125, 156)
ExAng 23 (14%) 76 (55%)
Oldpeak 0.20 (0.00, 1.03) 1.40 (0.55, 2.50)
Slope
    1 106 (65%) 36 (26%)
    2 49 (30%) 91 (65%)
    3 9 (5.5%) 12 (8.6%)
Ca
    0 130 (81%) 46 (33%)
    1 21 (13%) 44 (32%)
    2 7 (4.3%) 31 (22%)
    3 3 (1.9%) 17 (12%)
    Unknown 3 1
Thal
    fixed 6 (3.7%) 12 (8.7%)
    normal 129 (79%) 37 (27%)
    reversable 28 (17%) 89 (64%)
    Unknown 1 1
1 Median (IQR); n (%)
# Graphical summary:
# Heart %>% ggpairs()
# Load the pandas library
import pandas as pd
# Load numpy for array manipulation
import numpy as np
# Load seaborn plotting library
import seaborn as sns
import matplotlib.pyplot as plt

# Set font sizes in plots
sns.set(font_scale = 1.2)
# Display all columns
pd.set_option('display.max_columns', None)

Heart = pd.read_csv("Heart.csv")
Heart
     Unnamed: 0  Age  Sex     ChestPain  RestBP  Chol  Fbs  RestECG  MaxHR  \
0             1   63    1       typical     145   233    1        2    150   
1             2   67    1  asymptomatic     160   286    0        2    108   
2             3   67    1  asymptomatic     120   229    0        2    129   
3             4   37    1    nonanginal     130   250    0        0    187   
4             5   41    0    nontypical     130   204    0        2    172   
..          ...  ...  ...           ...     ...   ...  ...      ...    ...   
298         299   45    1       typical     110   264    0        0    132   
299         300   68    1  asymptomatic     144   193    1        0    141   
300         301   57    1  asymptomatic     130   131    0        0    115   
301         302   57    0    nontypical     130   236    0        2    174   
302         303   38    1    nonanginal     138   175    0        0    173   

     ExAng  Oldpeak  Slope   Ca        Thal  AHD  
0        0      2.3      3  0.0       fixed   No  
1        1      1.5      2  3.0      normal  Yes  
2        1      2.6      2  2.0  reversable  Yes  
3        0      3.5      3  0.0      normal   No  
4        0      1.4      1  0.0      normal   No  
..     ...      ...    ...  ...         ...  ...  
298      0      1.2      2  0.0  reversable  Yes  
299      0      3.4      2  2.0  reversable  Yes  
300      1      1.2      2  1.0  reversable  Yes  
301      0      0.0      2  1.0      normal  Yes  
302      0      0.0      1  NaN      normal   No  

[303 rows x 15 columns]
# Numerical summaries
Heart.describe(include = 'all')
        Unnamed: 0         Age         Sex     ChestPain      RestBP  \
count   303.000000  303.000000  303.000000           303  303.000000   
unique         NaN         NaN         NaN             4         NaN   
top            NaN         NaN         NaN  asymptomatic         NaN   
freq           NaN         NaN         NaN           144         NaN   
mean    152.000000   54.438944    0.679868           NaN  131.689769   
std      87.612784    9.038662    0.467299           NaN   17.599748   
min       1.000000   29.000000    0.000000           NaN   94.000000   
25%      76.500000   48.000000    0.000000           NaN  120.000000   
50%     152.000000   56.000000    1.000000           NaN  130.000000   
75%     227.500000   61.000000    1.000000           NaN  140.000000   
max     303.000000   77.000000    1.000000           NaN  200.000000   

              Chol         Fbs     RestECG       MaxHR       ExAng  \
count   303.000000  303.000000  303.000000  303.000000  303.000000   
unique         NaN         NaN         NaN         NaN         NaN   
top            NaN         NaN         NaN         NaN         NaN   
freq           NaN         NaN         NaN         NaN         NaN   
mean    246.693069    0.148515    0.990099  149.607261    0.326733   
std      51.776918    0.356198    0.994971   22.875003    0.469794   
min     126.000000    0.000000    0.000000   71.000000    0.000000   
25%     211.000000    0.000000    0.000000  133.500000    0.000000   
50%     241.000000    0.000000    1.000000  153.000000    0.000000   
75%     275.000000    0.000000    2.000000  166.000000    1.000000   
max     564.000000    1.000000    2.000000  202.000000    1.000000   

           Oldpeak       Slope          Ca    Thal  AHD  
count   303.000000  303.000000  299.000000     301  303  
unique         NaN         NaN         NaN       3    2  
top            NaN         NaN         NaN  normal   No  
freq           NaN         NaN         NaN     166  164  
mean      1.039604    1.600660    0.672241     NaN  NaN  
std       1.161075    0.616226    0.937438     NaN  NaN  
min       0.000000    1.000000    0.000000     NaN  NaN  
25%       0.000000    1.000000    0.000000     NaN  NaN  
50%       0.800000    2.000000    0.000000     NaN  NaN  
75%       1.600000    2.000000    1.000000     NaN  NaN  
max       6.200000    3.000000    3.000000     NaN  NaN  

Graphical summary:

# Graphical summaries
plt.figure()
sns.pairplot(data = Heart);
plt.show()

3 Initial split into test and non-test sets

We randomly split the data into 25% test data and 75% non-test data. Stratify on AHD.

# For reproducibility
set.seed(203)

data_split <- initial_split(
  Heart, 
  # stratify by AHD
  strata = "AHD", 
  prop = 0.75
  )
data_split
<Training/Testing/Total>
<227/76/303>
Heart_other <- training(data_split)
dim(Heart_other)
[1] 227  14
Heart_test <- testing(data_split)
dim(Heart_test)
[1] 76 14
from sklearn.model_selection import train_test_split

Heart_other, Heart_test = train_test_split(
  Heart, 
  train_size = 0.75,
  random_state = 425, # seed
  stratify = Heart.AHD
  )
Heart_test.shape
(76, 15)
Heart_other.shape
(227, 15)

Separate \(X\) and \(y\). We will use 13 features.

num_features = ['Age', 'Sex', 'RestBP', 'Chol', 'Fbs', 'RestECG', 'MaxHR', 'ExAng', 'Oldpeak', 'Slope', 'Ca']
cat_features = ['ChestPain', 'Thal']
features = np.concatenate([num_features, cat_features])
# Non-test X and y
X_other = Heart_other[features]
y_other = Heart_other.AHD == 'Yes'
# Test X and y
X_test = Heart_test[features]
y_test = Heart_test.AHD == 'Yes'

4 Recipe (R) and Preprocessing (Python)

  • A data dictionary (roughly) is at https://keras.io/examples/structured_data/structured_data_classification_with_feature_space/.

  • We have following features:

    • Numerical features: Age, RestBP, Chol, Slope (1, 2 or 3), MaxHR, ExAng, Oldpeak, Ca (0, 1, 2 or 3).

    • Categorical features coded as integer: Sex (0 or 1), Fbs (0 or 1), RestECG (0, 1 or 2).

    • Categorical features coded as string: ChestPain, Thal.

  • There are missing values in Ca and Thal. Since missing proportion is not high, we will use simple mean (for numerical feature Ca) and mode (for categorical feature Thal) imputation.

mlp_recipe <- 
  recipe(
    AHD ~ ., 
    data = Heart_other
  ) %>%
  # mean imputation for Ca
  step_impute_mean(Ca) %>%
  # mode imputation for Thal
  step_impute_mode(Thal) %>%
  # create traditional dummy variables (necessary for svm)
  step_dummy(all_nominal_predictors()) %>%
  # zero-variance filter
  step_zv(all_numeric_predictors()) %>% 
  # center and scale numeric data
  step_normalize(all_numeric_predictors()) %>%
  # estimate the means and standard deviations
  prep(training = Heart_other, retain = TRUE)
mlp_recipe

There are missing values in Ca (quantitative) and Thal (qualitative) variables. We are going to use simple mean imputation for Ca and most_frequent imputation for Thal. This is suboptimal. Better strategy is to use multiple imputation.

# How many NaNs
Heart.isna().sum()
Unnamed: 0    0
Age           0
Sex           0
ChestPain     0
RestBP        0
Chol          0
Fbs           0
RestECG       0
MaxHR         0
ExAng         0
Oldpeak       0
Slope         0
Ca            4
Thal          2
AHD           0
dtype: int64
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

# Transformer for categorical variables
categorical_tf = Pipeline(steps = [
  ("cat_impute", SimpleImputer(strategy = 'most_frequent')),
  ("encoder", OneHotEncoder(drop = 'first'))
])

# Transformer for continuous variables
numeric_tf = Pipeline(steps = [
  ("num_impute", SimpleImputer(strategy = 'mean')),
])

# Column transformer
col_tf = ColumnTransformer(transformers = [
  ('num', numeric_tf, num_features),
  ('cat', categorical_tf, cat_features)
])

5 Model

mlp_mod <- 
  mlp(
    mode = "classification",
    hidden_units = tune(),
    dropout = tune(),
    epochs = 50,
  ) %>% 
  set_engine("keras", verbose = 0)
mlp_mod
Single Layer Neural Network Model Specification (classification)

Main Arguments:
  hidden_units = tune()
  dropout = tune()
  epochs = 50

Engine-Specific Arguments:
  verbose = 0

Computational engine: keras 
from sklearn.neural_network import MLPClassifier

mlp_mod = MLPClassifier(
  hidden_layer_sizes = (8),
  solver = 'adam',
  batch_size = 16,
  validation_fraction = 0.0,
  random_state = 425
  )
mlp_mod  
MLPClassifier(batch_size=16, hidden_layer_sizes=8, random_state=425,
              validation_fraction=0.0)
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.

6 Workflow in R and pipeline in Python

Here we bundle the preprocessing step (Python) or recipe (R) and model.

mlp_wf <- workflow() %>%
  add_recipe(mlp_recipe) %>%
  add_model(mlp_mod)
mlp_wf
══ Workflow ════════════════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: mlp()

── Preprocessor ────────────────────────────────────────────────────────────────
5 Recipe Steps

• step_impute_mean()
• step_impute_mode()
• step_dummy()
• step_zv()
• step_normalize()

── Model ───────────────────────────────────────────────────────────────────────
Single Layer Neural Network Model Specification (classification)

Main Arguments:
  hidden_units = tune()
  dropout = tune()
  epochs = 50

Engine-Specific Arguments:
  verbose = 0

Computational engine: keras 
from sklearn.pipeline import Pipeline

pipe = Pipeline(steps = [
  ("col_tf", col_tf),
  ("model", mlp_mod)
  ])
pipe
Pipeline(steps=[('col_tf',
                 ColumnTransformer(transformers=[('num',
                                                  Pipeline(steps=[('num_impute',
                                                                   SimpleImputer())]),
                                                  ['Age', 'Sex', 'RestBP',
                                                   'Chol', 'Fbs', 'RestECG',
                                                   'MaxHR', 'ExAng', 'Oldpeak',
                                                   'Slope', 'Ca']),
                                                 ('cat',
                                                  Pipeline(steps=[('cat_impute',
                                                                   SimpleImputer(strategy='most_frequent')),
                                                                  ('encoder',
                                                                   OneHotEncoder(drop='first'))]),
                                                  ['ChestPain', 'Thal'])])),
                ('model',
                 MLPClassifier(batch_size=16, hidden_layer_sizes=8,
                               random_state=425, validation_fraction=0.0))])
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.

7 Tuning grid

Here we tune the cost and radial scale rbf_sigma.

param_grid <- grid_regular(
  hidden_units(range = c(1, 20)),
  dropout(range = c(0, 0.6)),
  levels = 5
  )
param_grid
# A tibble: 25 × 2
   hidden_units dropout
          <int>   <dbl>
 1            1    0   
 2            5    0   
 3           10    0   
 4           15    0   
 5           20    0   
 6            1    0.15
 7            5    0.15
 8           10    0.15
 9           15    0.15
10           20    0.15
# … with 15 more rows

Here we tune the inverse penalty strength C and the mixture parameter l1_ratio.

# Tune hyper-parameter(s)
hls_grid = [(1), (5), (10), (15), (20)] # hidden layer size
bs_grid = [4, 8, 12, 16, 20, 24, 28, 32] # batch sizes
tuned_parameters = {
  "model__hidden_layer_sizes": hls_grid,
  "model__batch_size": bs_grid
  }
tuned_parameters 
{'model__hidden_layer_sizes': [1, 5, 10, 15, 20], 'model__batch_size': [4, 8, 12, 16, 20, 24, 28, 32]}

8 Cross-validation (CV)

Set cross-validation partitions.

set.seed(203)

folds <- vfold_cv(Heart_other, v = 5)
folds
#  5-fold cross-validation 
# A tibble: 5 × 2
  splits           id   
  <list>           <chr>
1 <split [181/46]> Fold1
2 <split [181/46]> Fold2
3 <split [182/45]> Fold3
4 <split [182/45]> Fold4
5 <split [182/45]> Fold5

Fit cross-validation.

mlp_fit <- mlp_wf %>%
  tune_grid(
    resamples = folds,
    grid = param_grid,
    metrics = metric_set(roc_auc, accuracy)
    )
mlp_fit
# Tuning results
# 5-fold cross-validation 
# A tibble: 5 × 4
  splits           id    .metrics          .notes          
  <list>           <chr> <list>            <list>          
1 <split [181/46]> Fold1 <tibble [50 × 6]> <tibble [0 × 3]>
2 <split [181/46]> Fold2 <tibble [50 × 6]> <tibble [0 × 3]>
3 <split [182/45]> Fold3 <tibble [50 × 6]> <tibble [0 × 3]>
4 <split [182/45]> Fold4 <tibble [50 × 6]> <tibble [0 × 3]>
5 <split [182/45]> Fold5 <tibble [50 × 6]> <tibble [0 × 3]>

Visualize CV results:

mlp_fit %>%
  collect_metrics() %>%
  print(width = Inf) %>%
  filter(.metric == "roc_auc") %>%
  ggplot(mapping = aes(x = dropout, y = mean, alpha = hidden_units)) +
  geom_point() +
  labs(x = "Dropout Rate", y = "CV AUC") +
  scale_x_log10()
# A tibble: 50 × 8
   hidden_units dropout .metric  .estimator  mean     n std_err
          <int>   <dbl> <chr>    <chr>      <dbl> <int>   <dbl>
 1            1       0 accuracy binary     0.458     5  0.0242
 2            1       0 roc_auc  binary     0.5       5  0     
 3            5       0 accuracy binary     0.810     5  0.0319
 4            5       0 roc_auc  binary     0.901     5  0.0228
 5           10       0 accuracy binary     0.828     5  0.0216
 6           10       0 roc_auc  binary     0.920     5  0.0218
 7           15       0 accuracy binary     0.837     5  0.0241
 8           15       0 roc_auc  binary     0.906     5  0.0148
 9           20       0 accuracy binary     0.854     5  0.0184
10           20       0 roc_auc  binary     0.928     5  0.0122
   .config              
   <chr>                
 1 Preprocessor1_Model01
 2 Preprocessor1_Model01
 3 Preprocessor1_Model02
 4 Preprocessor1_Model02
 5 Preprocessor1_Model03
 6 Preprocessor1_Model03
 7 Preprocessor1_Model04
 8 Preprocessor1_Model04
 9 Preprocessor1_Model05
10 Preprocessor1_Model05
# … with 40 more rows
Warning: Transformation introduced infinite values in continuous x-axis

Show the top 5 models.

mlp_fit %>%
  show_best("roc_auc")
# A tibble: 5 × 8
  hidden_units dropout .metric .estimator  mean     n std_err .config           
         <int>   <dbl> <chr>   <chr>      <dbl> <int>   <dbl> <chr>             
1           20    0.6  roc_auc binary     0.932     5  0.0127 Preprocessor1_Mod…
2           20    0.45 roc_auc binary     0.931     5  0.0152 Preprocessor1_Mod…
3           10    0.15 roc_auc binary     0.929     5  0.0193 Preprocessor1_Mod…
4           20    0    roc_auc binary     0.928     5  0.0122 Preprocessor1_Mod…
5           20    0.15 roc_auc binary     0.927     5  0.0175 Preprocessor1_Mod…

Let’s select the best model.

best_mlp <- mlp_fit %>%
  select_best("roc_auc")
best_mlp
# A tibble: 1 × 3
  hidden_units dropout .config              
         <int>   <dbl> <chr>                
1           20     0.6 Preprocessor1_Model25

Set up CV partitions and CV criterion.

from sklearn.model_selection import GridSearchCV

# Set up CV
n_folds = 5
search = GridSearchCV(
  pipe,
  tuned_parameters,
  cv = n_folds, 
  scoring = "roc_auc",
  # Refit the best model on the whole data set
  refit = True
  )

Fit CV. This is typically the most time-consuming step.

# Fit CV
search.fit(X_other, y_other)
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('col_tf',
                                        ColumnTransformer(transformers=[('num',
                                                                         Pipeline(steps=[('num_impute',
                                                                                          SimpleImputer())]),
                                                                         ['Age',
                                                                          'Sex',
                                                                          'RestBP',
                                                                          'Chol',
                                                                          'Fbs',
                                                                          'RestECG',
                                                                          'MaxHR',
                                                                          'ExAng',
                                                                          'Oldpeak',
                                                                          'Slope',
                                                                          'Ca']),
                                                                        ('cat',
                                                                         Pipeline(steps=[('cat_impute',
                                                                                          SimpleImputer(strategy='most_frequent')),
                                                                                         ('encoder',
                                                                                          OneHotEncoder(drop='first'))]),
                                                                         ['ChestPain',
                                                                          'Thal'])])),
                                       ('model',
                                        MLPClassifier(batch_size=16,
                                                      hidden_layer_sizes=8,
                                                      random_state=425,
                                                      validation_fraction=0.0))]),
             param_grid={'model__batch_size': [4, 8, 12, 16, 20, 24, 28, 32],
                         'model__hidden_layer_sizes': [1, 5, 10, 15, 20]},
             scoring='roc_auc')
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.

Visualize CV results.

Code
cv_res = pd.DataFrame({
  "bs": np.array(search.cv_results_["param_model__batch_size"]),
  "auc": search.cv_results_["mean_test_score"],
  "hls": search.cv_results_["param_model__hidden_layer_sizes"]
  })

plt.figure()
sns.relplot(
  # kind = "line",
  data = cv_res,
  x = "bs",
  y = "auc",
  hue = "hls"
  ).set(
    # xscale = "log",
    xlabel = "Batch Size",
    ylabel = "CV AUC"
    );
plt.show()

Best CV AUC:

search.best_score_
0.910431746031746

The training accuracy is

from sklearn.metrics import accuracy_score, roc_auc_score

accuracy_score(
  y_other,
  search.best_estimator_.predict(X_other)
  )
0.8325991189427313

9 Finalize our model

Now we are done tuning. Finally, let’s fit this final model to the whole training data and use our test data to estimate the model performance we expect to see with new data.

# Final workflow
final_wf <- mlp_wf %>%
  finalize_workflow(best_mlp)
final_wf
══ Workflow ════════════════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: mlp()

── Preprocessor ────────────────────────────────────────────────────────────────
5 Recipe Steps

• step_impute_mean()
• step_impute_mode()
• step_dummy()
• step_zv()
• step_normalize()

── Model ───────────────────────────────────────────────────────────────────────
Single Layer Neural Network Model Specification (classification)

Main Arguments:
  hidden_units = 20
  dropout = 0.6
  epochs = 50

Engine-Specific Arguments:
  verbose = 0

Computational engine: keras 
# Fit the whole training set, then predict the test cases
final_fit <- 
  final_wf %>%
  last_fit(data_split)
final_fit
# Resampling results
# Manual resampling 
# A tibble: 1 × 6
  splits           id               .metrics .notes   .predictions .workflow 
  <list>           <chr>            <list>   <list>   <list>       <list>    
1 <split [227/76]> train/test split <tibble> <tibble> <tibble>     <workflow>
# Test metrics
final_fit %>% 
  collect_metrics()
# A tibble: 2 × 4
  .metric  .estimator .estimate .config             
  <chr>    <chr>          <dbl> <chr>               
1 accuracy binary         0.539 Preprocessor1_Model1
2 roc_auc  binary         0.832 Preprocessor1_Model1

Since we called GridSearchCV with refit = True, the best model fit on the whole non-test data is readily available.

search.best_estimator_
Pipeline(steps=[('col_tf',
                 ColumnTransformer(transformers=[('num',
                                                  Pipeline(steps=[('num_impute',
                                                                   SimpleImputer())]),
                                                  ['Age', 'Sex', 'RestBP',
                                                   'Chol', 'Fbs', 'RestECG',
                                                   'MaxHR', 'ExAng', 'Oldpeak',
                                                   'Slope', 'Ca']),
                                                 ('cat',
                                                  Pipeline(steps=[('cat_impute',
                                                                   SimpleImputer(strategy='most_frequent')),
                                                                  ('encoder',
                                                                   OneHotEncoder(drop='first'))]),
                                                  ['ChestPain', 'Thal'])])),
                ('model',
                 MLPClassifier(batch_size=4, hidden_layer_sizes=5,
                               random_state=425, validation_fraction=0.0))])
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.

The final AUC on the test set is

roc_auc_score(
  y_test,
  search.best_estimator_.predict_proba(X_test)[:, 1]
  )
0.935191637630662

The final classification accuracy on the test set is

accuracy_score(
  y_test,
  search.best_estimator_.predict(X_test)
  )
0.8552631578947368