In [1]:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import wfdb
import os
import time
from sklearn.manifold import TSNE
from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold, StratifiedKFold, GridSearchCV, cross_val_score, cross_validate
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn import svm
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from sklearn.dummy import DummyClassifier
from sklearn.preprocessing import LabelEncoder

import matplotlib.colors as mcolors
In [2]:
%load_ext ipycache

Loading the dataset The wfdb library is used to process the special ECG files. The signal and annotations are stored in different files. The annotations include information about the peaks which are used to identify the individual heart beats and take a predefined window size around this peak which then makes up the signal of an individual heart beat. The labels that belong each peak are stored with the data of the signals itself in a dictionary.

In [3]:
from src.preprocessing import preprocess_record_to_dataframe
from src.config import DATASET_PATH, OUTPUT_PATH, WINDOW_SIZE

os.makedirs(OUTPUT_PATH, exist_ok=True)

# List of records to process
record_names = [f.replace('.dat', '') for f in os.listdir(DATASET_PATH) if f.endswith('.dat')]

all_heartbeats = []

for record_name in record_names:
    heartbeats = preprocess_record_to_dataframe(record_name)
    for heartbeat, label in heartbeats:
        all_heartbeats.append({
            **{i: val for i, val in enumerate(heartbeat)},  # Signal values as features
            "label": label                                                # Annotation as label
        })

The data is then stored in a DataFrame and some lables are dropped:

  • [!] indicates Ventricular flutter wave which is a life-threatening arrhytmia that shows a rapid wave like pattern without distinguishable P waves, QRS complexes or T waves[1] which is why it is not suitable for the classification of individual heart beats.
  • Q stands for "unclassifiable beat". This project focuses on beats that can be clearly classified by a human professional. Edge cases might be suitable for future investigations to the topic.
  • the meaning of ~, ", + is not stated in the official description which is why they are removed as well.

Furthermore, the labels are replaced by the official name as stated on the official website for increased interpretability.


[1] : Smirk FH, Nolla-Panades J, Wallis T. Experimental ventricular flutter and ventricular paroxysmal tachycardia. The American Journal of Cardiology [Online]. 1964;14(1):79–88. Available from: https://doi.org/10.1016/0002-9149(64)90110-9.

In [4]:
from src.config import class_to_name

# Create the dataframe
raw = pd.DataFrame(all_heartbeats)

# drop rows with certain labels
raw = raw[~raw['label'].isin(['[', '!', ']', '~', '"', "Q", "+"])]

# Replace annotation symbols with names
raw['label'] = raw['label'].replace(class_to_name)


raw.head()
Out[4]:
0 1 2 3 4 5 6 7 8 9 ... 191 192 193 194 195 196 197 198 199 label
1 -0.010 -0.010 -0.010 -0.010 -0.010 -0.010 -0.010 -0.010 -0.010 -0.035 ... 0.300 0.275 0.250 0.230 0.000 0.000 0.000 0.000 0.00 Normal
2 -0.640 -0.615 -0.585 -0.560 -0.540 -0.515 -0.480 -0.440 -0.395 -0.355 ... -0.090 -0.110 -0.135 -0.170 -0.195 -0.205 -0.240 -0.245 -0.25 Normal
3 -0.555 -0.555 -0.565 -0.590 -0.600 -0.600 -0.605 -0.595 -0.595 -0.575 ... 0.185 0.190 0.185 0.200 0.220 0.215 0.215 0.195 0.19 Normal
4 0.220 0.215 0.215 0.195 0.190 0.165 0.155 0.150 0.155 0.125 ... 0.210 0.185 0.200 0.195 0.190 0.190 0.170 0.160 0.14 Normal
5 0.135 0.120 0.100 0.095 0.075 0.040 0.005 -0.025 -0.050 -0.075 ... 0.305 0.325 0.330 0.340 0.335 0.320 0.305 0.270 0.24 Normal

5 rows × 201 columns

Initial Data Analysis¶

In [5]:
%%cache -r ecg_signals_plot.pkl raw_long
# plot each class

# pivot wide to long
raw_long = pd.melt(raw, id_vars="label", value_vars=[i for i in range(200)])
# plot ecg signal for each class with seaborn
raw_long = raw_long.rename(columns={"variable": "time", "value": "ECG signal in mV"})
plt.figure(figsize=(20, 10))
sns.lineplot(
    data=raw_long,
    x="time",
    y="ECG signal in mV",
    hue="label",
)
raw_long = raw_long.rename(columns={"ECG signal in mV": "signal"})
plt.show()
[Skipped the cell's code and loaded variables raw_long from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/ecg_signals_plot.pkl'.]
No description has been provided for this image

This plot shows the average heart beat of each class. As can be seen, there is some noticable difference between the average signal of each class.

In [6]:
%%cache -r ecg_signals_plot_reduced.pkl raw_long_reduced
raw_reduced = raw.apply(lambda x: x[::4], axis=1)
raw_long_reduced = pd.melt(raw_reduced, id_vars="label", value_vars=[i for i in range(0,200,4)])
# plot ecg signal for each class with seaborn
raw_long_reduced = raw_long_reduced.rename(columns={"variable": "time", "value": "ECG signal in mV"})
plt.figure(figsize=(20, 10))
sns.lineplot(
    data=raw_long_reduced,
    x="time",
    y="ECG signal in mV",
    hue="label",
)
raw_long_reduced = raw_long_reduced.rename(columns={"ECG signal in mV": "signal"})
plt.show()
[Skipped the cell's code and loaded variables raw_long_reduced from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/ecg_signals_plot_reduced.pkl'.]
No description has been provided for this image

The plot above shows the again the signals for each class. However, this time only every fourth data point is considered. As can be seen, the major differences between the classes are still noticable with this reduced resolution. Reducing the dimensionality might help to avoid side effects of the curse of dimensionality and to reduce the run time for the algorithms.

This reduced dimensionality will be used for the training of the SVM later on.

In [7]:
%%cache -r stacked_bar_plot.pkl
# create stacked bar plot
raw.groupby(['label']).size().plot(kind='barh', stacked=True, figsize=(10, 5))
[Skipped the cell's code and loaded variables  from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/stacked_bar_plot.pkl'.]
No description has been provided for this image

The plot above shows that the classes are extremely imbalanced with the normal class being the most common one by far. Furthermore, it can be seen that some classes are very rare. Therefore, some classes with very few samples will be removed from the dataset.

In [8]:
raw.groupby('label').size()
Out[8]:
label
Aberrated atrial premature beat            150
Atrial escape beat                          16
Atrial premature beat                     2546
Fusion of paced and normal beat            982
Fusion of ventricular and normal beat      803
Isolated QRS-like artifact                 132
Left bundle branch block beat             8075
Nodal (junctional) escape beat             312
Non-conducted P-wave (blocked APB)         193
Normal                                   75052
Paced beat                                7028
Premature ventricular contraction         7130
Right bundle branch block beat            7259
Supraventricular premature beat              2
Ventricular escape beat                    106
dtype: int64
In [9]:
# plot random samples for each class
grp = raw.groupby('label')
fig = plt.figure(figsize=(20, 5*len(grp.mean())))
for i, (name, group) in enumerate(grp):
    plt.subplot(len(grp.mean()), 3, i+1)
    plt.plot(group.sample(1, random_state=42).values[0, :-1], color='r')
    # plt average normal signal for comparison
    plt.plot(grp.mean().loc['Normal'].values[:-1], color='gray')
    plt.title(name)
No description has been provided for this image

Above is a random example of every class to get an intuition about their differences. The average of a normally classified heart beat is plotted as a frame of references to understand the main deviations.

Exploratory Data Analysis and Preprocessing¶

In [10]:
stats = raw_long[['label', 'signal']].groupby('label').agg(['mean', 'std', 'min', 'max'])[['signal']]#.sort_values(('signal', 'count'), ascending=False)
stats
Out[10]:
signal
mean std min max
label
Aberrated atrial premature beat -0.114359 0.249495 -1.800 2.260
Atrial escape beat -0.484669 0.449446 -1.135 1.970
Atrial premature beat -0.215938 0.318788 -2.755 2.835
Fusion of paced and normal beat -0.184681 0.371750 -2.545 2.600
Fusion of ventricular and normal beat -0.196133 0.659906 -2.260 3.285
Isolated QRS-like artifact -0.235213 0.648768 -3.175 2.460
Left bundle branch block beat -0.198187 0.465604 -3.955 3.130
Nodal (junctional) escape beat -0.212347 0.376803 -1.870 2.230
Non-conducted P-wave (blocked APB) -0.529764 0.650697 -2.340 2.450
Normal -0.333637 0.461340 -5.120 5.115
Paced beat -0.311993 0.599345 -3.365 3.465
Premature ventricular contraction -0.254767 0.726543 -3.605 3.640
Right bundle branch block beat -0.506218 0.554128 -3.090 2.595
Supraventricular premature beat -0.160888 0.306135 -0.540 1.545
Ventricular escape beat -0.112904 0.345731 -0.735 1.105
In [11]:
%%cache -r boxplot.pkl

plt.figure(figsize=(20, 10))
# remove 0 values
sns.boxplot(data=raw_long[raw_long['signal'] != 0], x='label', y='signal')
plt.show()
[Skipped the cell's code and loaded variables  from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/boxplot.pkl'.]
No description has been provided for this image

The box plot shows that combining all dimensions into one does not reveal much difference between classes, as the value of an individual feature seems to depend more on the position of the feature than on the class itself. Only looking at the whole signal, as in the previous plots, reveals the differences.

As mentioned before, there are some classes with very few values. For the purposes of this project, only classes with more than 500 heartbeats are selected. This is a choice for quality of classification over quantity of classification. This leaves a total of 8 classes.

For the future, the model presented here can easily be adapted to fit more classes.

In [12]:
X = raw.drop('label', axis=1)
y = raw['label']

class_counts = y.value_counts()

# Filter out classes with less than 100 entries
valid_classes = class_counts[class_counts >= 500].index
X = X[y.isin(valid_classes)]
y = y[y.isin(valid_classes)]
valid_classes
Out[12]:
Index(['Normal', 'Left bundle branch block beat',
       'Right bundle branch block beat', 'Premature ventricular contraction',
       'Paced beat', 'Atrial premature beat',
       'Fusion of paced and normal beat',
       'Fusion of ventricular and normal beat'],
      dtype='object', name='label')

In the following, some dimensionality reductions are performed to better understand the structure of the data.

In [14]:
from src.visualization import plot_dimension_reduction
# use PCA to reduce the dimensionality of the data
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_scaled = StandardScaler().fit_transform(X)
X_pca = pca.fit_transform(X_scaled)
X_pca = pd.DataFrame(X_pca, columns=['x', 'y'])
X_pca['label'] = raw['label']
plot_dimension_reduction(X_pca)
No description has been provided for this image

The PCA transformation does not show clearly distinct groups data points belonging to the same class. However, in the UMAP dimensionality reduction, data point belonging to the same class are grouped together which gives hope that classification will be possible as there seems to be some detectable similarity between the classes.

In [15]:
# umap 
import umap
reducer = umap.UMAP()
X_umap = reducer.fit_transform(X_scaled)
X_umap = pd.DataFrame(X_umap, columns=['x', 'y'])
X_umap['label'] = raw['label']
plot_dimension_reduction(X_umap)
/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
No description has been provided for this image

Baselines and Learning Curves¶

The two algorithms chosen for this project are SMV and Random Forest. The Baseline will be the most frequent class because the data is un equally distributed and therefore choosing the most frequent class would be the best choice without looking at the data.

In [16]:
from src.config import random_state
Cs = [0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000]

For the SVM, the dimensionality is reduced due to long run times and the data is also scaled. Despite the fact that all features have the same unit and are therefore comparable, it has been show to be useful to still scale the data for SVM training as is increases performance and reduces run time. 1

For the Random Forest which is a collection of decision trees, it is not necessary to scale the data. Additionally, the resolution is not reduced here in the same way as for the SVMs because one hyperparameter test is feature bagging which selects a subset of features and therefore trains each tree with a reduces dimensionality.


  1. Edwards, Catherine and Bhavani Raskutti. “The Effect of Attribute Scaling on the Performance of Support Vector Machines.” Australian Conference on Artificial Intelligence (2004).

Support Vector Machines (RDF kernel)¶

  • C
  • gamma

Test C¶

In [20]:
%%cache -r results_C.pkl results_C

from src.training import simple_cross_val
num_splits = 5
num_repeats = 3

results_C = simple_cross_val(svm.SVC(kernel='rbf', random_state=random_state, class_weight='balanced'), X, y, Cs, 'estimator__C', num_splits=num_splits, num_repeats=num_repeats)
[Skipped the cell's code and loaded variables results_C from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/results_C.pkl'.]
Processing estimator__C with value 0.001 in 52.8 minutes
Processing estimator__C with value 0.01 in 54.9 minutes
Processing estimator__C with value 0.1 in 26.3 minutes
Processing estimator__C with value 1 in 15.4 minutes
Processing estimator__C with value 10 in 10.6 minutes
Processing estimator__C with value 100 in 10.0 minutes
Processing estimator__C with value 1000 in 12.0 minutes
Processing estimator__C with value 10000 in 12.9 minutes

The f1 weighted score of the baseline was not tested in the loop and is therefore added now. It is expected to be almost the same for all folds and repetition due to stratified splits and is therefore simply averaged.

In [21]:
num_splits = 5
num_repeats = 3
baseline_f1_weigted = cross_val_score(DummyClassifier(strategy='most_frequent'), X, y, scoring='f1_weighted', cv=RepeatedStratifiedKFold(n_splits=num_splits, n_repeats=num_repeats, random_state=random_state), n_jobs=-1)
print(f'Baseline F1 weighted minimum value: {baseline_f1_weigted.min()}')
print(f'Baseline F1 weighted maximum value: {baseline_f1_weigted.max()}')
results_C['dummy_test_f1_weighted'] = baseline_f1_weigted.mean()
results_C.groupby('estimator__C').mean(['test_balanced_accuracy', 'train_balanced_accuracy', 'test_f1_weighted', 'train_f1_weighted']).sort_values('test_f1_weighted', ascending=False)
Baseline F1 weighted minimum value: 0.5625517189826944
Baseline F1 weighted maximum value: 0.5626113838171476
Out[21]:
fit_time score_time test_balanced_accuracy train_balanced_accuracy test_accuracy train_accuracy test_recall_weighted train_recall_weighted test_f1_weighted train_f1_weighted dummy_test_score dummy_test_f1_weighted
estimator__C
100 117.292975 36.577381 0.939548 0.974466 0.987953 0.995916 0.987953 0.995916 0.987763 0.995833 0.125 0.562576
1000 190.434317 32.509753 0.945452 0.991179 0.987313 0.998380 0.987313 0.998380 0.987245 0.998364 0.125 0.562576
10000 242.622557 28.417697 0.945551 0.998203 0.985739 0.999635 0.985739 0.999635 0.985769 0.999634 0.125 0.562576
10 109.906960 44.984089 0.919309 0.935531 0.985739 0.990037 0.985739 0.990037 0.985268 0.989663 0.125 0.562576
1 130.214965 61.486515 0.853424 0.859742 0.974576 0.976512 0.974576 0.976512 0.973429 0.975439 0.125 0.562576
0.1 257.233805 108.932344 0.672771 0.674369 0.949104 0.949702 0.949104 0.949702 0.938044 0.938727 0.125 0.562576
0.01 661.207884 193.517074 0.533505 0.533726 0.905454 0.905595 0.905454 0.905595 0.884522 0.884681 0.125 0.562576
0.001 590.458263 213.536609 0.155150 0.155442 0.705016 0.705167 0.705016 0.705167 0.595804 0.596087 0.125 0.562576
In [22]:
from src.visualization import plot_learning_curve
plot_learning_curve(results_C, 'estimator__C')
No description has been provided for this image

The performance for both balanced accuracy and f1 weighted increases for larger numbers of C. However, the curve stagnates and reaches a training balanced accuracy of almost 1.0. The f1 weighted test scores decrease slightly with values larger than 100 which indicates overfitting because the training scores are still increasing. All parameters tested are better than the baseline.

For the nested cross-validation, values smaller than 0.1 are disregarded due to their poor performance.

Test gamma¶

In [23]:
%%cache -r results_gamma.pkl results_gamma
gammas =  ['scale', 0.001, 0.01, 0.1, 1.0, 10.0]
num_splits = 5
num_repeats = 3

results_gamma = simple_cross_val(svm.SVC(kernel='rbf', random_state=random_state, class_weight='balanced'), X, y, gammas, param_name='estimator__gamma', num_splits=num_splits, num_repeats=num_repeats)
[Skipped the cell's code and loaded variables results_gamma from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/results_gamma.pkl'.]
Processing estimator__gamma with value scale in 13.0 minutes
Processing estimator__gamma with value 0.001 in 35.7 minutes
Processing estimator__gamma with value 0.01 in 15.8 minutes
Processing estimator__gamma with value 0.1 in 16.3 minutes
Processing estimator__gamma with value 1.0 in 146.9 minutes
Processing estimator__gamma with value 10.0 in 475.8 minutes
In [24]:
results_gamma['dummy_test_f1_weighted'] = baseline_f1_weigted.mean()
results_gamma.groupby('estimator__gamma').mean(['test_balanced_accuracy', 'train_balanced_accuracy', 'test_f1_weighted', 'train_f1_weighted']).sort_values('test_f1_weighted', ascending=False)
Out[24]:
fit_time score_time test_balanced_accuracy train_balanced_accuracy test_accuracy train_accuracy test_recall_weighted train_recall_weighted test_f1_weighted train_f1_weighted dummy_test_score dummy_test_f1_weighted
estimator__gamma
0.1 220.757814 54.030272 0.914298 0.935576 0.984447 0.990470 0.984447 0.990470 0.983996 0.990127 0.125 0.562576
scale 104.277766 54.111543 0.853424 0.859742 0.974576 0.976512 0.974576 0.976512 0.973429 0.975439 0.125 0.562576
0.01 138.642302 67.214211 0.805511 0.810625 0.968370 0.969546 0.968370 0.969546 0.966325 0.967598 0.125 0.562576
1.0 3696.256375 146.866619 0.727841 0.983796 0.929947 0.997972 0.929947 0.997972 0.924320 0.997946 0.125 0.562576
0.001 330.799500 147.465249 0.596347 0.596966 0.921776 0.922089 0.921776 0.922089 0.905331 0.905697 0.125 0.562576
10.0 12609.410481 350.119459 0.222770 0.999781 0.729883 0.999964 0.729883 0.999964 0.644147 0.999964 0.125 0.562576
In [25]:
plot_learning_curve(results_gamma, 'estimator__gamma')
No description has been provided for this image

The learning curves show that for all hyperparameter values of gamma the performance is better than the baseline. The maximum balanced accuracy and f1 weighted is at a value of 0.1 for gamma. For higher values, the classifier seems to overfit the training data, as the training performance continues to increase while the test performance decreases. The error due to bias decreases while the error due to variance increases. Out of the tested values, a value of 0.1 for gamma seems to be the best trade-off between these two forms of error.

The 'scale' value is a special case because it takes into account the variance and therefore depends on the training data. It is calculated by $$\frac{1}{n_{features} \cdot var(X)}$$ which depends on the variance of the training data and therefore on the split. The 'scale' value gave the second best result.

For the nested cross-validation, all values except the gamma of 10 are used because a value of 10 had by far the worst results.

Random Forest¶

In [26]:
%%cache -r results_n_estimators.pkl results_n_estimators

n_estimators =  [1, 5, 10, 50, 100, 200, 500]
num_splits = 5
num_repeats = 3

results_n_estimators = simple_cross_val(BaggingClassifier(estimator=DecisionTreeClassifier(random_state=random_state, class_weight='balanced'), random_state=random_state), X, y, n_estimators, param_name='estimator__n_estimators', num_splits=num_splits, num_repeats=num_repeats)
[Skipped the cell's code and loaded variables results_n_estimators from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/results_n_estimators.pkl'.]
Processing estimator__n_estimators with value 1 in 0.7 minutes
Processing estimator__n_estimators with value 5 in 3.8 minutes
Processing estimator__n_estimators with value 10 in 7.0 minutes
Processing estimator__n_estimators with value 50 in 35.2 minutes
Processing estimator__n_estimators with value 100 in 74.4 minutes
Processing estimator__n_estimators with value 200 in 143.8 minutes
Processing estimator__n_estimators with value 500 in 361.1 minutes
In [27]:
results_n_estimators['estimator'].iloc[0]
Out[27]:
Pipeline(steps=[('estimator',
                 BaggingClassifier(estimator=DecisionTreeClassifier(random_state=42),
                                   n_estimators=1, random_state=42))])
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.
Pipeline(steps=[('estimator',
                 BaggingClassifier(estimator=DecisionTreeClassifier(random_state=42),
                                   n_estimators=1, random_state=42))])
BaggingClassifier(estimator=DecisionTreeClassifier(random_state=42),
                  n_estimators=1, random_state=42)
DecisionTreeClassifier(random_state=42)
DecisionTreeClassifier(random_state=42)
In [28]:
results_n_estimators['dummy_test_f1_weighted'] = baseline_f1_weigted.mean()
results_n_estimators.groupby('estimator__n_estimators').mean('test_balanced_accuracy').sort_values('test_balanced_accuracy', ascending=False)
Out[28]:
fit_time score_time test_balanced_accuracy train_balanced_accuracy test_accuracy train_accuracy test_recall_weighted train_recall_weighted test_f1_weighted train_f1_weighted dummy_test_score dummy_test_f1_weighted
estimator__n_estimators
200 4288.273874 2.997994 0.877034 1.000000 0.977699 1.000000 0.977699 1.000000 0.976818 1.000000 0.125 0.562576
500 10721.415357 7.781597 0.876839 1.000000 0.977730 1.000000 0.977730 1.000000 0.976843 1.000000 0.125 0.562576
50 1034.795088 1.075778 0.876527 0.999667 0.977307 0.999952 0.977307 0.999952 0.976426 0.999952 0.125 0.562576
100 2206.868193 2.093817 0.875498 0.999936 0.977359 0.999992 0.977359 0.999992 0.976458 0.999992 0.125 0.562576
10 205.967545 0.495407 0.875454 0.993439 0.975109 0.998692 0.975109 0.998692 0.974346 0.998689 0.125 0.562576
5 110.789138 0.516601 0.866465 0.981364 0.970853 0.996371 0.970853 0.996371 0.970152 0.996353 0.125 0.562576
1 18.248644 0.342640 0.829012 0.936513 0.950953 0.982155 0.950953 0.982155 0.951145 0.982173 0.125 0.562576
In [29]:
plot_learning_curve(results_n_estimators, 'estimator__n_estimators')
No description has been provided for this image

All tested values are much better than the baseline. A value of 200 for the number of estimators had the highest average balanced accuracy. However, the performance differences between values of 10, 50, 100, 200 and 500 are so small that they could be due to chance and might not be reproducible. In this case it has to be taken into account that a larger number of estimators is associated with a longer running time, both in training and in prediction. Another observation is that the classifier overfits the data for all tested values. This is because the training performance is higher than the test performance.

For the nested cross-validation, all parameter values except 100 and 500 are selected. 500 is discarded because it has a much longer run time without a better performance in this case. 200 is kept above 100 because a high number of estimators combined with a lower number of maximum features (bagging) could be a way to counteract overfitting.

In [30]:
%%cache -r max_feature.pkl results_max_feature
max_features = [0.1, 0.2, 0.5, 0.8, 1.0]
num_splits = 5
num_repeats = 3
results_max_feature = simple_cross_val(BaggingClassifier(estimator=DecisionTreeClassifier(random_state=random_state, class_weight='balanced'), random_state=random_state), X, y, max_features, param_name='estimator__max_features', num_splits=num_splits, num_repeats=num_repeats)
[Skipped the cell's code and loaded variables results_max_feature from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/max_feature.pkl'.]
Processing estimator__max_features with value 0.1 in 0.6 minutes
Processing estimator__max_features with value 0.2 in 1.2 minutes
Processing estimator__max_features with value 0.5 in 2.7 minutes
Processing estimator__max_features with value 0.8 in 3.6 minutes
Processing estimator__max_features with value 1.0 in 4.0 minutes
In [31]:
results_max_feature['dummy_test_f1_weighted'] = baseline_f1_weigted.mean()
results_max_feature.groupby('estimator__max_features').mean('test_balanced_accuracy').sort_values('test_balanced_accuracy', ascending=False)
Out[31]:
fit_time score_time test_balanced_accuracy train_balanced_accuracy test_accuracy train_accuracy test_recall_weighted train_recall_weighted test_f1_weighted train_f1_weighted dummy_test_score dummy_test_f1_weighted
estimator__max_features
0.5 74.937432 0.781085 0.882929 0.994447 0.978045 0.998905 0.978045 0.998905 0.977289 0.998904 0.125 0.562576
0.8 104.340963 0.524740 0.880720 0.994071 0.976882 0.998796 0.976882 0.998796 0.976131 0.998794 0.125 0.562576
1.0 116.993953 0.539640 0.878775 0.993976 0.975979 0.998749 0.975979 0.998749 0.975232 0.998747 0.125 0.562576
0.2 30.439438 0.599837 0.874374 0.994554 0.977531 0.999010 0.977531 0.999010 0.976600 0.999008 0.125 0.562576
0.1 12.338217 1.017890 0.851373 0.993363 0.974270 0.998856 0.974270 0.998856 0.972960 0.998853 0.125 0.562576
In [32]:
plot_learning_curve(results_max_feature, 'estimator__max_features')
No description has been provided for this image

The best value for the number of features is 0.5 in this case. However, the differences are rather small.

Nested Cross Validation¶

One take away apart from the best hyperparameter range for each algorithm is that the training is very time consuming. Since the nested cross validation is much more time consuming than the simple cross validation, the following will estimate run time for the nested cross validation and take a few adjustments to reduce the time.

Runtime Nested Cross-Validation¶

SVM¶

SVM average run time:

The average time is estimated by averaging over all the simple cross-validations performed previously. This approximation is not perfect because some parameter combinations may take longer or shorter than those tested, but this information is missing. $$t_{svm} = \frac{52.8 + 54.9 + 26.3 + 15.4 + 10.6 + 10.0 + 12.0 + 12.9 + 13.0 + 35.7 + 15.8 + 16.3 + 146.9 + 475.8}{14 \cdot \text{split} \cdot \text{repeat}} \approx 4.2 min$$

Nested cross validation with grid search: In general, the more outer/internal splits and random repeats, the better, as the results are more reliable and the effect of randomness is reduced when looking at the overall results. The following shows the estimated runtime for 10 internal splits, 10 external splits, 10 random repeats in the internal cross-validation and 10 random repeats in the external cross-validation. $$ t_{nested}(t_{svm}) = \text{num Cs} \cdot \text{num gammas} \cdot \text{inner splits} \cdot \text{inner repeats} \cdot \text{outer splits} \cdot \text{outer repeats} \cdot t_{svm}$$ $$ = 5 \cdot 5 \cdot 10 \cdot 10 \cdot 10 \cdot 10 \cdot 4.2 min \approx 1,050,000 min \approx 17,500h \approx 729d$$

This is an unacceptably long time. Therefore, two measures are taken to reduce the time:

  1. Reduce the number of splits and repeats:

$$ t_{nested}(t_{svm}) = \text{num Cs} \cdot \text{num gammas} \cdot \text{inner splits} \cdot \text{inner repeats} \cdot \text{outer splits} \cdot \text{outer repeats} \cdot t_{svm}$$ $$ t_{nested}(t_{svm}) \approx 5 \cdot 5 \cdot 3 \cdot 3 \cdot 5 \cdot 3 \cdot 4.2 min = 14.175 min \approx 236,25h \approx 9,8d$$

  1. Reduce dataset from 108875 to 41898: The time complexity of svm training in LibSVM1 (which is the implementation in sklearn)2 is $O(n^2 \cdot m)$3 where $n$ is the number of samples and $m$ is the number of features.

Since $m$ is the same for both and only $n$ changes, we can calculate the expected run time in the following way: $$\frac{T_2}{T_1} \approx (\frac{n_2}{n_1})^2$$ $$T_2 \approx T_1 \cdot (\frac{n_2}{n_1})^2$$ $$T_2 \approx 14175 \cdot (\frac{41898}{108875})^2 \approx 2099 min \approx 34h$$

Finally, this run time is acceptable and therefore the following experiments will use this set up.


  1. Chang, Chih-Chung and Chih-Jen Lin. “LIBSVM: A library for support vector machines.” ACM Trans. Intell. Syst. Technol. 2 (2011): 27:1-27:27.
  2. https://scikit-learn.org/1.5/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC
  3. Abdiansah, Abdiansah and Retantyo Wardoyo. “Time Complexity Analysis of Support Vector Machines (SVM) in LibSVM.” International Journal of Computer Applications 128 (2015): 28-34.

Random Forest¶

The hyperparameters of the nested cross-validation and the size of the dataset are the same as for the SVM for reasons of comparability. However, the number of parameters tested and the expected run time will be calculated in the following to make an informed choice

The run of a single random forest run is estimated similarly to the SVM. Again, this is just an approximation as the combination of parameters might differ. $$t_{rf} =\frac{0.7 + 3.8 + 7.0 + 35.2 + 74.4+ 143.8 + 1.0 + 1.6 + 5.0 + 6.9 + 7.6}{11 \cdot 5 \cdot 3} = 1.7$$ $$t_{nested} = 5 \cdot 6 \cdot 3 \cdot 3 \cdot 5 \cdot 3 \cdot 1.7 = 6885 min = 114h$$

Below are a few options presented to reduce the run time which take the results of the simple cross-validation into account.

With smaller dataset: The effect in time reduction of the smaller dataset is not as much as for the SVM since the random forest scales linearly with number of training samples.1 $$6885 \cdot \frac{41898}{108875} \approx 2649min \approx 44h$$

without n_estimators = 100: $$t_{rf} =\frac{0.7 + 3.8 + 7.0 + 35.2 + 143.8 + 1.0 + 1.6 + 5.0 + 6.9 + 7.6}{10 \cdot 5 \cdot 3} = 1.4$$ $$t_{nested} = 5 \cdot 5 \cdot 3 \cdot 3 \cdot 5 \cdot 3 \cdot 1.4 = 4725 min$$

with smaller dataset: $$ 4725 \cdot \frac{41898}{108875} = 1818 min = 30h$$

wihtout n_estimators = 100 and max_features = 0.8: $$t_{rf} =\frac{0.7 + 3.8 + 7.0 + 35.2 + 143.8 + 1.0 + 1.6 + 5.0 + 7.6}{9 \cdot 5 \cdot 3} = 1.5$$ $$t_{nested} = 4 \cdot 5 \cdot 3 \cdot 3 \cdot 5 \cdot 3 \cdot 1.5 = 4050 min$$

with smaller dataset: $$ 4050 \cdot \frac{41898}{108875} = 1558 min = 25,9h$$

without n_estimators = 200: $$t_{rf} =\frac{0.7 + 3.8 + 7.0 + 35.2 + 74.4+ 1.0 + 1.6 + 5.0 + 6.9 + 7.6}{10 \cdot 5 \cdot 3} = 0.95 min$$ $$t_{nested} = 5 \cdot 5 \cdot 3 \cdot 3 \cdot 5 \cdot 3 \cdot 1.4 = 3206 min$$

with smaller dataset: $$3206 \cdot \frac{41898}{108875} = 1233 min = 20h$$

The option without 100 as a value for the number of estimators and with out 80% for the max features seems the be the best option with regards to run time and the results of the simple cross-validation.


  1. Gossen, Frederik and Bernhard Steffen. “Algebraic aggregation of random forests: towards explainability and rapid evaluation.” International Journal on Software Tools for Technology Transfer 25 (2021): 267-285.
In [33]:
# reduce normal class to the size of the largest other class
raw_small  = raw.groupby('label').apply(lambda x: x.sample(8075, random_state=14, replace=False) if x['label'].values[0] == 'Normal' else x, include_groups=True).reset_index(drop=True)
X_small = raw_small.drop('label', axis=1)
y_small = raw_small['label']
X_small = X_small[y_small.isin(valid_classes)]
y_small = y_small[y_small.isin(valid_classes)]
y_small.value_counts()
/var/folders/jf/ydr4sg4d3bb248_vyfbfdycw0000gn/T/ipykernel_19437/3236997221.py:2: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.
  raw_small  = raw.groupby('label').apply(lambda x: x.sample(8075, random_state=14, replace=False) if x['label'].values[0] == 'Normal' else x, include_groups=True).reset_index(drop=True)
Out[33]:
label
Left bundle branch block beat            8075
Normal                                   8075
Right bundle branch block beat           7259
Premature ventricular contraction        7130
Paced beat                               7028
Atrial premature beat                    2546
Fusion of paced and normal beat           982
Fusion of ventricular and normal beat     803
Name: count, dtype: int64

Since the dataset is imbalanced and some classes already have a low number of data points, the dataset is reduced by reducing the 'Normal' class to the size of the larges other class which is 8075 in this case. This can be seen as a form of downsampling because it also creates a more balanced dataset. For the practical implications, it is probably more important to correctly classify an abnormal heart beat which further justifies this reduction.

In [34]:
from sklearn.model_selection import GridSearchCV, cross_validate, RepeatedStratifiedKFold, StratifiedKFold
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
from src.training import nested_cv

from src.config import NUM_RANDOM_REPEATS_OUTER, NUM_RANDOM_REPEATS_INNER, NUM_SPLITS_OUTER, NUM_SPLITS_INNER

SVM¶

In [35]:
print(f"The size of the original dataset is {len(X)} and the length of the reduced dataset is {len(X_small)}.")
The size of the original dataset is 108875 and the length of the reduced dataset is 41898.
In [36]:
%%cache -r nested_results_svm.pkl results_svm
Cs = [0.1, 1, 10, 100, 1000]
gammas =  ['scale', 0.001, 0.01, 0.1, 1.0]
param_grid_svm = {'estimator__C': Cs, 'estimator__gamma': gammas}
results_svm = nested_cv(svm.SVC(kernel='rbf', random_state=random_state, class_weight='balanced'), param_grid_svm, X_small, y_small)
[Skipped the cell's code and loaded variables results_svm from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/nested_results_svm.pkl'.]
Starting nested cross validation with a dataset of size: 41898
Repetition 0 finished after 583.66 minutes
Repetition 1 finished after 1194.13 minutes
Repetition 2 finished after 1797.62 minutes

Random Forest¶

In [37]:
%%cache -r nested_results_rf.pkl results_rf

n_estimators =  [1, 5, 10, 50, 200]
max_features = [0.1, 0.2, 0.5, 1.0]


param_grid_rf = {'estimator__n_estimators': n_estimators, 'estimator__max_features': max_features}
results_rf = nested_cv(BaggingClassifier(DecisionTreeClassifier(random_state=random_state, class_weight='balanced')random_state=random_state), param_grid_rf, X_small, y_small)
[Skipped the cell's code and loaded variables results_rf from file '/Users/lisa/Documents/DataScienceMaster/machine_learning/ml_project/nested_results_rf.pkl'.]
Starting nested cross validation with a dataset of size: 41898
Repetition 0 finished after 663.69 min
Repetition 1 finished after 1314.99 min
Repetition 2 finished after 1980.84 min

Evaluation¶

In [38]:
from src.evaluation import transform_nested_cv_results

results_svm = transform_nested_cv_results(results_svm, 'estimator__C', 'estimator__gamma')
results_svm
Out[38]:
fit_time score_time estimator test_accuracy train_accuracy test_balanced_accuracy train_balanced_accuracy train_score_0 test_score_0 train_score_1 test_score_1 train_score_2 test_score_2 estimator__C estimator__gamma
0 6942.869781 4.637104 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.978043 0.995763 0.950923 0.990213 [0.7291967621812812, 0.4347807886363245, 0.630... [0.7240067071973033, 0.4345386862889289, 0.621... [0.737890438855215, 0.44600133768348416, 0.632... [0.7316942209660564, 0.44348964795567763, 0.63... [0.7381555456895168, 0.4441778623913728, 0.627... [0.7320879988227185, 0.4447750618078928, 0.627... 10 0.1
1 7210.767083 4.073274 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.975179 0.999433 0.953267 0.998956 [0.7348772436487586, 0.4320375781714261, 0.641... [0.7247249536600044, 0.4293792685034513, 0.636... [0.7268485371867837, 0.44353246866853757, 0.63... [0.7330170804108371, 0.44153853394404446, 0.64... [0.7312190855197841, 0.4399324565276721, 0.631... [0.7277518468592763, 0.4439344942133995, 0.620... 100 0.1
2 6886.986292 4.343214 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.976969 0.995555 0.945328 0.989458 [0.737352219092037, 0.43907525299193934, 0.647... [0.7297192780022927, 0.4420967221042132, 0.632... [0.7345549834326994, 0.4460992340279817, 0.637... [0.7298210482760081, 0.4402818947751865, 0.636... [0.7358983482092207, 0.4443793259385917, 0.634... [0.7358683999421631, 0.4470318377722986, 0.645... 10 0.1
3 6948.642021 4.353699 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.978040 0.999493 0.948514 0.999121 [0.738366284651787, 0.4361216433160101, 0.6529... [0.7288500659879704, 0.43521999428326474, 0.64... [0.7297051005600381, 0.4439675574183233, 0.626... [0.7274045399103966, 0.43865317716666746, 0.62... [0.7347262099560573, 0.4457428260076972, 0.638... [0.7320080845116744, 0.4497513595878131, 0.642... 100 0.1
4 6920.720982 4.364116 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.976728 0.999463 0.955436 0.999019 [0.7362233577310184, 0.4390620170348965, 0.632... [0.7305340756216628, 0.44277004016210647, 0.62... [0.7337032049886572, 0.446098180652321, 0.6362... [0.7338848699009514, 0.43865126047831754, 0.63... [0.740339528153376, 0.4436859911723915, 0.6316... [0.7365097081377746, 0.4469855163701358, 0.630... 100 0.1
0 7369.782913 4.521828 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.975418 0.999582 0.946700 0.999346 [0.7335303826738342, 0.4442185871159168, 0.625... [0.735958398593623, 0.4456635712663455, 0.6253... [0.7340743256214624, 0.4457831566924446, 0.627... [0.7353269714265446, 0.44128284312801885, 0.62... [0.7437394240302352, 0.44053739419263316, 0.65... [0.722448864407881, 0.44239525512047, 0.642389... 100 0.1
1 7261.235737 2.532580 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.972792 0.998270 0.944605 0.996752 [0.7357618785631408, 0.4427143789669443, 0.636... [0.7409219233605894, 0.4463232928434606, 0.644... [0.7312945442067558, 0.44668898707648935, 0.65... [0.7354190883037066, 0.44265519408579684, 0.65... [0.7334626915815811, 0.4402818283448584, 0.655... [0.7221374901010611, 0.43780857653975663, 0.64... 1000 scale
2 7026.852493 2.911020 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.975776 0.998180 0.955774 0.996290 [0.7346879896397573, 0.4461487201622979, 0.629... [0.7312535675473211, 0.4393712578584361, 0.628... [0.7365879507286557, 0.44223433262697953, 0.63... [0.7414465039412699, 0.4408125527769042, 0.635... [0.7365452843427469, 0.43963716923141943, 0.64... [0.727233097835795, 0.44407808884422606, 0.638... 1000 scale
3 7618.255924 2.785423 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.975773 0.997941 0.954808 0.995669 [0.7410544241038401, 0.444109470517974, 0.6329... [0.7306784937935102, 0.4479801157636761, 0.636... [0.7278495334987996, 0.4368515181362448, 0.632... [0.7333991366036015, 0.43388231986978715, 0.63... [0.7276585678281008, 0.4399813215188422, 0.639... [0.7276377194804733, 0.43765160442366113, 0.63... 1000 scale
4 7264.747166 4.395005 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.977324 0.999373 0.957231 0.998875 [0.7370393194997011, 0.44396993223543096, 0.62... [0.73047883230879, 0.44439395481375066, 0.6288... [0.732886642116598, 0.43900266222791207, 0.626... [0.7409471113598319, 0.4382103334950499, 0.626... [0.7320193475460053, 0.4408387911861278, 0.644... [0.7201394004883745, 0.43790891177010605, 0.63... 100 0.1
0 7265.075111 2.565106 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.973986 0.998001 0.950627 0.996015 [0.7286997894464169, 0.44091214704860426, 0.63... [0.7345460624649891, 0.4413674713188353, 0.642... [0.7396284728907352, 0.4385487201393886, 0.632... [0.7245397073504987, 0.44001766081176263, 0.62... [0.7392924818162298, 0.4398675509842743, 0.642... [0.726989853805752, 0.4377724844441654, 0.6389... 1000 scale
1 7295.060783 2.687549 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.974105 0.995734 0.946317 0.990050 [0.732589310852267, 0.4439372781414889, 0.6337... [0.7391530234432954, 0.44507630024098765, 0.64... [0.7353543572458481, 0.4440136249732562, 0.640... [0.737533809434743, 0.4435253626886023, 0.6398... [0.7363781422532268, 0.44340869563996765, 0.64... [0.7268608909923233, 0.44180972725694084, 0.63... 1000 0.01
2 7044.282819 4.489103 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.977446 0.999523 0.947906 0.999140 [0.7307717123330165, 0.4415205927732444, 0.629... [0.748100107153447, 0.44139697970140573, 0.637... [0.7451886924276978, 0.43873172894042095, 0.64... [0.7343745179235417, 0.44256801210534363, 0.63... [0.7445239589702259, 0.43866526364638253, 0.64... [0.732416034716434, 0.4339159131205118, 0.6359... 100 0.1
3 7334.398363 2.716289 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.978398 0.998031 0.963473 0.995851 [0.7266376734784117, 0.4436104040556139, 0.627... [0.7246329207280111, 0.44372501641856016, 0.62... [0.7305710384220335, 0.440998773228015, 0.6324... [0.7243170692911338, 0.44676297260381737, 0.62... [0.7341244059769949, 0.4474511277608942, 0.642... [0.7313556974166893, 0.44033897635203, 0.63914... 1000 scale
4 7194.723067 2.868654 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.977086 0.993496 0.952960 0.984703 [0.7329826841099862, 0.4472265372253117, 0.628... [0.7305024209268562, 0.44369474375632223, 0.62... [0.7321871005195244, 0.43963773765121483, 0.63... [0.7307597535708875, 0.44918265335482593, 0.63... [0.7369122150231495, 0.44219309034608734, 0.63... [0.7297344821177603, 0.43690581841260184, 0.62... 100 scale
In [39]:
results_rf = transform_nested_cv_results(results_rf.copy(), 'estimator__n_estimators', 'estimator__max_features')
results_rf
Out[39]:
fit_time score_time estimator test_balanced_accuracy train_balanced_accuracy test_f1_weighted train_f1_weighted train_score_0 test_score_0 train_score_1 test_score_1 train_score_2 test_score_2 estimator__n_estimators estimator__max_features
0 7961.887177 0.392842 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.920441 1.0 0.968048 1.0 [0.9025312802086516, 0.9871483945607153, 0.997... [0.7358751826792216, 0.869292307362759, 0.8835... [0.906974321205176, 0.9889699012049871, 0.9973... [0.7496420120432334, 0.875538132714432, 0.8869... [0.9091083108890409, 0.9879095689213833, 0.997... [0.7449407754722476, 0.8719289552326663, 0.888... 200 0.2
1 7917.780969 0.125428 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.932692 1.0 0.968459 1.0 [0.9055492345860157, 0.9872396564826033, 0.997... [0.7371010110432326, 0.8655558240952732, 0.886... [0.8981108195881761, 0.9866856416906123, 0.996... [0.7250197367330713, 0.8696750636143855, 0.888... [0.902386115380458, 0.9863000608108904, 0.9966... [0.7378781205639326, 0.8640412851991075, 0.886... 50 0.2
2 8048.032054 0.263344 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.910577 1.0 0.966838 1.0 [0.9025736947417418, 0.9871260819115683, 0.998... [0.7385486553852361, 0.8729890395762756, 0.883... [0.9045312073655666, 0.9879697773446852, 0.996... [0.7524025642025254, 0.8778510843869859, 0.898... [0.9107327940151734, 0.9870220539677045, 0.997... [0.7553259075633822, 0.8752468390070482, 0.893... 200 0.2
3 8007.378162 0.224469 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.914961 1.0 0.967141 1.0 [0.9078713580941757, 0.9882704380665344, 0.996... [0.7421277470895286, 0.8671710323354075, 0.887... [0.9035941888898078, 0.9876693224610877, 0.998... [0.7468858879423741, 0.875630504687841, 0.8901... [0.906686878951259, 0.9880389002352646, 0.9968... [0.7505606519548904, 0.8801158824663842, 0.902... 200 0.2
4 7881.490530 0.170494 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.910421 1.0 0.966792 1.0 [0.9080696103673874, 0.987475032502846, 0.9970... [0.7347727656809059, 0.868715113205403, 0.8803... [0.9044726338397175, 0.9884389121645115, 0.997... [0.7490368126510061, 0.8864704421795861, 0.896... [0.9079864324496971, 0.9869153974505278, 0.996... [0.7377436333407854, 0.8765836167964483, 0.894... 200 0.2
0 7803.055252 0.165050 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.923311 1.0 0.967737 1.0 [0.9087029738526728, 0.9854799690596318, 0.997... [0.7525388297450892, 0.886674195657151, 0.8996... [0.9086207438355004, 0.9887169974788037, 0.997... [0.7526614042883499, 0.876276448466597, 0.8895... [0.9071607239320301, 0.9884757993230903, 0.997... [0.7512297438358422, 0.8736787623978681, 0.883... 200 0.2
1 7735.676100 0.164175 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.909402 1.0 0.965479 1.0 [0.9026698192072573, 0.9887577314964673, 0.997... [0.7416422545559991, 0.8718278297091042, 0.887... [0.9027808219462662, 0.9901539124426884, 0.996... [0.7481999005076667, 0.8738061314628525, 0.883... [0.9074471607020943, 0.987486800598087, 0.9970... [0.7456146316913008, 0.8819772382774057, 0.895... 200 0.2
2 7739.294327 0.164955 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.913798 1.0 0.967245 1.0 [0.9055778520053004, 0.9854294846175689, 0.998... [0.7394134060943455, 0.8700268676154579, 0.883... [0.912209947985489, 0.9898416509975616, 0.9973... [0.7553247182023901, 0.8785158297936946, 0.893... [0.907165337126598, 0.9903449968637785, 0.9979... [0.7468619859484176, 0.8830380960389164, 0.897... 200 0.2
3 7830.892279 0.165094 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.927057 1.0 0.969429 1.0 [0.9035437200426518, 0.9882629762683355, 0.998... [0.7405455443052714, 0.8725093755383087, 0.888... [0.8981387833388849, 0.9864844254445486, 0.997... [0.7476302961685916, 0.8754723093562524, 0.900... [0.9063635793643775, 0.9876383525506569, 0.997... [0.7345626444479627, 0.8696656722678029, 0.893... 200 0.2
4 7964.371016 0.216501 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.925516 1.0 0.968138 1.0 [0.9079829591247226, 0.9894222851346598, 0.997... [0.7417435233711132, 0.8787337617670345, 0.898... [0.9078451466742908, 0.9883708414806031, 0.997... [0.7485627934462847, 0.8735598888667908, 0.887... [0.9029556141271169, 0.9886146134498784, 0.997... [0.7276377299417032, 0.8662353141107592, 0.880... 200 0.2
0 8196.238059 0.238429 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.923404 1.0 0.967914 1.0 [0.9058623790049809, 0.9882978125016435, 0.998... [0.7512413946941138, 0.8820396471032402, 0.895... [0.9087284107150732, 0.9854118697796999, 0.997... [0.742278517127104, 0.8685149810912329, 0.8826... [0.9090107733083312, 0.9858514533574801, 0.997... [0.7512379617972336, 0.8724006812860847, 0.889... 200 0.2
1 7853.884210 0.262043 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.911257 1.0 0.966100 1.0 [0.9055471569194833, 0.986820966517185, 0.9972... [0.7511280260082025, 0.8700936897238277, 0.884... [0.9004577059620744, 0.9878003854710614, 0.997... [0.7417448887675684, 0.8753205615959915, 0.893... [0.9087127111299824, 0.9875802190478389, 0.997... [0.7483133944794543, 0.874007519239041, 0.8918... 200 0.2
2 8004.298786 0.267960 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.914156 1.0 0.967116 1.0 [0.908816401586937, 0.9892166024409882, 0.9972... [0.7493810574418092, 0.8880433764654839, 0.890... [0.9091444718747901, 0.9878490158193893, 0.997... [0.7361378637870376, 0.8734833109396878, 0.890... [0.9072167695449262, 0.9873400557684483, 0.996... [0.7380866337466145, 0.8696141023452305, 0.884... 200 0.2
3 7768.459298 0.111582 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.932068 1.0 0.969228 1.0 [0.9039029643749174, 0.9881591371727356, 0.998... [0.7416067749771782, 0.8786703773359756, 0.897... [0.9112548499247617, 0.986247576051676, 0.9973... [0.7511743210318236, 0.8794239287700376, 0.889... [0.9086613413299391, 0.9890637093192924, 0.998... [0.7409833357037023, 0.8697463391825921, 0.879... 50 0.2
4 8123.437893 0.224697 GridSearchCV(cv=RepeatedStratifiedKFold(n_repe... 0.919083 1.0 0.967893 1.0 [0.9089861159956629, 0.9889581726778354, 0.996... [0.7477738427174824, 0.8752308060909466, 0.886... [0.9057467632318468, 0.9896187809275045, 0.997... [0.7477889712667221, 0.8776613866822488, 0.891... [0.9074812919481972, 0.9886091262179288, 0.997... [0.7313162755905622, 0.8679117974121302, 0.888... 200 0.2
In [40]:
import sklearn
sklearn.set_config(enable_metadata_routing=True)

from sklearn.metrics import f1_score


f1_weighted = []
for i in range(NUM_RANDOM_REPEATS_OUTER):
        outer_cv = StratifiedKFold(n_splits=NUM_SPLITS_OUTER, random_state=i, shuffle=True)
        for fold_idx, (train_idx, test_idx) in enumerate(outer_cv.split(X_small, y_small)):
            X_test, y_test = X.iloc[test_idx], y.iloc[test_idx]
            best_estimator = results_svm['estimator'][fold_idx].iloc[i]
            f1_weighted.append(f1_score(y_test, best_estimator.predict(X_test), average='weighted'))
results_svm['test_f1_weighted'] = f1_weighted
In [41]:
from src.visualization import comparison_plot

fig, ax = comparison_plot(results_svm, results_rf, 'test_balanced_accuracy', 'test_f1_weighted')
No description has been provided for this image

The evaluation of the nested cross-validation shows that the SVM performs better than the Random Forest in all the best models of each GridSearch. Depending on the fold and random repeat of the outer cross-validation, the optimal parameter combination might vary. In fact, there are five different parameter combinations in total. Possible reasons for this ambiguity in hyperparameter setting of the SVM will be discussed later on.

In [42]:
fig, ax = comparison_plot(results_svm, results_rf, 'fit_time', 'score_time')
ax[0].set_ylabel('time in seconds')
ax[1].set_ylabel('time in seconds')
Out[42]:
Text(0, 0.5, 'time in seconds')
No description has been provided for this image

Looking at the fit time also reveals that the SVM are faster during training but slower during score time. In practice, when evaluating long term ECG, the score time is not as relevant since it is still sufficiently fast. However, if the model is used in an ambulance for emergency situations on a device with limited computational power, then the score time would play a bigger role.

In [43]:
from src.visualization import plot_scores

plot_scores(results_svm, 'estimator__C', 'estimator__gamma', 'SVM')
No description has been provided for this image

This plot shows that the ambiguity about the optimal hyperparameters might be due to several maxima in hyperparameter combination that are close to each other. However, the variance between different runs is quite small with multiple hyperparameter combinations yielding good results and reproducible results.

In [44]:
print(f"The variance of the test balanced accuracy for the SVM is {results_svm['test_balanced_accuracy'].var()}")
The variance of the test balanced accuracy for the SVM is 2.746391563527743e-05
In [45]:
plot_scores(results_rf, 'estimator__n_estimators', 'estimator__max_features', 'Random Forest')
No description has been provided for this image

All the best models of the Random Forest had a max_feature value of 0.2, but the graph above shows that it seems to have only a slight advantage over other values. Using only one estimator had the worst performance overall. It is also interesting that the variance between different runs is twice as high as for the SVM.

In [46]:
print(f"The variance of the test balanced accuracy for the Random Forest is {results_rf['test_balanced_accuracy'].var()}")
The variance of the test balanced accuracy for the Random Forest is 6.203502733147229e-05

Analysis of the Final Model¶

Confusion Matrices SVM¶

In [47]:
# Confusion matrix for best model
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.metrics import RocCurveDisplay, auc

from src.visualization import plot_confusion_matrix_agg
    
plot_confusion_matrix_agg(results_svm, 'sum')
        
No description has been provided for this image

The normalized confusion matrix shows that some Atrial premature beats are misclassified as Normal beats. The paced beat is the most least misclassified beat. In general, there seem to be few misclassifications overall and no concerning patterns.

In [48]:
plot_confusion_matrix_agg(results_svm, 'variance')
No description has been provided for this image

The highest variance between classifications is again for classifying Atrial premature beat as Normal. This might mean that there are a few Atrial premature beats that are close to the signal of a Normal beat and depending on wheather they are in the split or not, there are more or less misclasifications here.

Confusion Matrices Random Forest¶

In [49]:
plot_confusion_matrix_agg(results_rf, 'sum')
No description has been provided for this image

For the Random Forests, the most misclassified class is again the Atrial premature beat which is confused with a normal beat. This shows that this misclassification is not specific to the estimator and appears in different estimators which might be due to data samples that are very similar to the normal class.

In [50]:
plot_confusion_matrix_agg(results_rf, 'variance')
No description has been provided for this image

Misclassifications¶

In [54]:
from src.evaluation import get_misclassifications
mis_X, mis_y_true, mis_y_pred = get_misclassifications(results_svm, X_small, y_small)
    
Fold 0 finished with 184 misclassifications
Fold 1 finished with 208 misclassifications
Fold 2 finished with 193 misclassifications
Fold 3 finished with 184 misclassifications
Fold 4 finished with 195 misclassifications
Fold 0 finished with 206 misclassifications
Fold 1 finished with 228 misclassifications
Fold 2 finished with 203 misclassifications
Fold 3 finished with 203 misclassifications
Fold 4 finished with 190 misclassifications
Fold 0 finished with 218 misclassifications
Fold 1 finished with 217 misclassifications
Fold 2 finished with 189 misclassifications
Fold 3 finished with 181 misclassifications
Fold 4 finished with 192 misclassifications
In [55]:
df_true = pd.concat(mis_X)
df_true['label'] = pd.concat(mis_y_true)

df_pred = df_true.copy()
df_pred['label'] = np.concatenate(mis_y_pred, axis=0)

# Plotting the misclassifications for each class
fig, ax = plt.subplots(4, 2, figsize=(20, 30))
ax = ax.flatten()
for i, clazz in enumerate(df_true['label'].unique()):
    group = df_true[df_true['label'] == clazz]
    group = group.drop('label', axis=1)
    s = group.sample(1, random_state=random_state)
    idx = s.index[0]
    if type(df_pred.loc[idx, 'label']) == str:
        prediced_class = df_pred.loc[idx, 'label']
    else: 
        prediced_class = df_pred.loc[idx, 'label'].iloc[0]
    ax[i].plot(s.T, color='r', label='Misclassification')
    ax[i].plot(raw[raw['label'] == clazz].drop('label', axis=1).mean(), color='green', label=f'True avg: {clazz}')
    ax[i].plot(raw[raw['label'] == prediced_class].drop('label', axis=1).mean(), color='blue', label=f'Pred avg: {prediced_class}')
    ax[i].legend()
    ax[i].set_title(clazz)
    ax[i].set_xlabel('Time')
    ax[i].set_ylabel('ECG signal in mV')
No description has been provided for this image

The Plot above shows a random misclassification of each class. For some samples, the data seems to be closer to the average prediced class than to the true class. This might be one reason why they are misclassified. The true classification might depend on minor details that the model misses in these selected cases.

In [68]:
# ROC curve normal vs abnormal
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import LabelBinarizer

from src.visualization import plot_roc_curve
fig, ax = plot_roc_curve(results_svm, svm.SVC(kernel='rbf', random_state=random_state, probability=True, class_weight='balanced'), X_small, y_small)
No description has been provided for this image

The ROC curves show promising very good results with high AUC scores for all classes.

In [ ]:
from matplotlib.colors import ListedColormap
import umap


# plot decision boundaries
mapper = umap.UMAP(random_state=random_state).fit(X_small)
X_embedded = mapper.transform(X_small)
clf = results_svm['estimator'].iloc[0]

from src.visualization import plot_decisions
plot_decisions(X_small, X_embedded, y_small, results_svm['estimator'].iloc[0], mapper)
/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
No description has been provided for this image

The visualization above shows how the decision boundaries could look like when projected into a two dimensional space. However, a lot of information is lost when projecting the data into such a low dimensional space and the the projection of the grid into a high dimensional space is also rather approximate. The grid probably contains many point that, when projected into the high dimensional space, are physically impossible ECG signals due to for example extremly high values for some dimensions. Furthermore, the inverse mapping of UMAP does not gurantee to retrieve the exact original data because it is a non-linear dimensionality reduction technique.

However, it is interesting to see that the normal class is somewhat in the middle between the other classes. Which makes a lot of sense since most classes are described as some form of deviation from the normal classes.

In [66]:
#%%cache -f decision_boundaries.pkl
# plot decision boundaries
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_scaled = StandardScaler().fit_transform(X_small)
X_pca = pca.fit_transform(X_scaled)
#X_pca = pd.DataFrame(X_pca, columns=['x', 'y'])
plot_decisions(X_small, X_pca, y_small, results_svm['estimator'].iloc[1], pca)
No description has been provided for this image

Production¶

In [ ]:
%%cache -f final_model.pkl clf

from src.production import train_prod_model

Cs = [0.1, 1, 10, 100, 1000]
gammas =  ['scale', 0.001, 0.01, 0.1, 1.0]
param_grid_svm = {'estimator__C': Cs, 'estimator__gamma': gammas}
clf = train_prod_model(svm.SVC(kernel='rbf', random_state=random_state), param_grid_svm, X, y,)

Conclusions and Future Work¶

Summary of the results:¶

The SVM had a better performance in terms of balanced accuracy and F1 weighted on the test data. It had a faster training time than the best Random Forest models, but a longer evaluation time.

Generated Value:¶

The value generated is that ECG beat signals can be classified with high accuracy without human intervention. The classifier can help doctors analyse large amounts of ECG data generated during long-term ECGs. It could potentially take off some workload of cardiologists who only analyze the summer of the recording and not every individual heart beat. Although it would be good to have a model trained with all possible classifications in this case.

Future directions:¶

With more data, the classification can be extended to cover a larger variety of samples. Furthermore, it might be interesting to diagnose more complex patterns in ECG data. This project focused on the classification of single beats but it takes more than a single beat to diagnose a disease of the heart. So it would be interesting to analyze patterns that continue over multiple beats like for example ventricular flutter. It would also be interesting to assess the risk of heart disease based on the ECG patterns, as different characteristics of the ECG signals may be predictors. 1

In terms of the classifier itself, it would be interesting to use deep learning structures such as RNN, LSTM or Transformer, which are good for sequential structures. This could be especially good if the time frame of observation is extended. It might also be worth trying class-specific scaling, as it has shown good performance for SVMs in other scenarios.2 Furthermore, it may be promising to perform dimensionality reduction prior to classification.

For real-world applications, it would also be good to have a classifier that also detects edge cases. This means that the classifier classifies the certain samples and leaves the uncertain or ambiguous samples to the cardiologist. The probability output from an SVM or Random Forest is not explicitly designed to measure confidence, so it may be better to use Bayesian neural networks or other Bayesian classifiers.

Reflection:¶

For practical implementation, it would also be necessary to automatically detect the peaks of the heartbeats, as this is essential for detecting the signal of an individual heartbeat. For practical implementation, it would be good to have a model that is more general in that it can classify all existing heartbeat annotations and perhaps even more long-term patterns.

Although the dataset is more than 100,000 samples, the data comes from only 47 subjects. The question is how much the phenotype of the class depends on the individual. There should have been more replicates and splits in the nested cross-validation. However, this was not possible for this project due to time and computational constraints.

Classes with less than 500 samples are not considered. In retrospect, this threshold could have been lowered to include more classes.

To get a better understanding of the best choice of hyperparameters, it would have been good to try more hyperparameters during the simple cross-validation.

It might have been better to do the downsampling before the simple cross validation, as the optimal hyperparameter range might be slightly different for a dataset with a different balance.


  1. Rautaharju, Pentti M., Charles L. Kooperberg, Joseph C. Larson and Andrea Z. LaCroix. “Electrocardiographic Abnormalities That Predict Coronary Heart Disease Events and Mortality in Postmenopausal Women: The Women’s Health Initiative.” Circulation 113 (2006): 473-480.
  2. Edwards, Catherine and Bhavani Raskutti. “The Effect of Attribute Scaling on the Performance of Support Vector Machines.” Australian Conference on Artificial Intelligence (2004).