The Data¶

In [ ]:
import os
import copy
import time
import random
import torch
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle as cPickle
import pandas as pd
from sklearn.metrics import ConfusionMatrixDisplay, accuracy_score

from torch.utils.data import DataLoader, Dataset, SubsetRandomSampler

from torch.utils.tensorboard import SummaryWriter

torch.set_default_dtype(torch.float)
pd.options.display.max_columns = None

# results are cached to avoid re-running the same code
import ipycache
%load_ext ipycache


import warnings
warnings.filterwarnings('ignore')


from src.config import RANDOM_SEED, BATCH_SIZE, NUM_EPOCHS, NUM_WORKERS, VALIDATION_RATIO, TEST_SIZE


os.environ["PL_GLOBAL_SEED"] = str(RANDOM_SEED)
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
torch.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed_all(RANDOM_SEED)

The Dataset contains mass spectrometry samples of different bacteria from a variety of different species. The features are the mass spectrometry mass-to-charge ratios binned to 6000 values. This results in an array of the measured intensity for every of the 6000 mass-to-charge ratios (m/z). The labels are the resistances / sensitivities to the specific antibiotic. Given that bacteria can exhibit multiple resistances or sensitivities, this classification is binary and multi-label.

This data is suitable for the proposal because it includes both mass spectrometry recordings and antibiotic resistance data.

Key challenges:

  • Multi label classification
  • Many missing values in the labels

The data for this task is retrieved from the DRIAMS Database1,2 which provides a substantial amount of measurements from both mass spectra of bacteria and the corresponding antibiotic resistance information. The data is organized into the following folder structure:

DRIAMS
├── DRIAMS-A
│   ├── binned_6000
│   ├── id
│   ├── preprocessed
│   └── raw
├── DRIAMS-B
│   ├── binned_6000
│   ├── id
│   ├── preprocessed
│   └── raw
├── DRIAMS-C
│   ├── binned_6000
│   ├── id
│   ├── preprocessed
│   └── raw
└── DRIAMS-D
    ├── binned_6000
    ├── id
    ├── preprocessed
    └── raw

The folders labeled DIRAMS-A, DIRAMS-B, DIRAMS-C and DIRAMS-D represent four distinct subsets from various institutions in Switzerland. The id folders contain the CSV files with metadata such as species and antibiotic resistance information. The raw folders contain the mass spectra measurements without any processing, while the preprocessed folder contains the mass spectra measurements with an established preprocessing applied. The binned_6000 folder contains the preprocessed samples binned along the mass-to-charge ratio axis to 6,000 feature bins. In this project, only the mass spectra frequencies from the binned_6000 folders are used. This approach ensures that all samples possess the same dimensionality, a key benefit for model design as it facilitates enhanced flexibility.


  1. C. Weis, A. Cuénod, B. Rieck, K. Borgwardt, and A. Egli, “DRIAMS: Database of Resistance Information on Antimicrobials and MALDI-TOF Mass Spectra.” Dryad, p. 144838557987 bytes, Nov. 01, 2021. doi: 10.5061/DRYAD.BZKH1899Q.
  2. C. Weis et al., “Direct antimicrobial resistance prediction from clinical MALDI-TOF mass spectra using machine learning,” Nat Med, vol. 28, no. 1, pp. 164–174, Jan. 2022, doi: 10.1038/s41591-021-01619-9.
In [38]:
data_path = "/Volumes/FESTPLATTE/DL_project_data/archive"

dfs_labels = []
paths = []

for root, dirs, files in os.walk(data_path, topdown=False):
    for name in files:
        # read in all csv files with metadata and antibiotic resistance information
        if name.endswith("clean.csv"):
            df = pd.read_csv(os.path.join(root, name))
            dfs_labels.append(df)
        # read in all txt files with mass spectrometry data from the binned_6000 folders
        elif name.endswith(".txt") and "binned_6000" in root:
            paths.append(os.path.join(root, name))

raw_data = pd.concat(dfs_labels, ignore_index=True, join="inner")
In [88]:
raw_data.head()
Out[88]:
species Piperacillin-Tazobactam Meropenem Ciprofloxacin Cefepime Ceftazidime Amikacin Levofloxacin Imipenem Ceftriaxone Clindamycin Amoxicillin-Clavulanic acid Vancomycin Erythromycin Tetracycline Ertapenem Norfloxacin Nitrofurantoin Linezolid Teicoplanin Tigecycline Daptomycin Gentamicin Cefuroxime Oxacillin Rifampicin Fusidic acid Mupirocin Fosfomycin
code
74969164-613a-4455-ac8e-5666ee0dfade MIX!Streptococcus pneumoniae NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
e9adf43d-679b-497c-9849-1fa214838dd3 Staphylococcus epidermidis R R R R - - - R R S R S S R - - - S R S S R R R S R - NaN
926aea1e-27c2-410c-8f2a-ff00f2e9e585 Enterococcus faecalis - - - - - - S S - - - S - - - - - S S S - - - - - - - NaN
c110440a-17b1-4c35-964a-0870217ebe40 Staphylococcus epidermidis NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3755ec08-5951-46f9-b8eb-bcdccc2fd8ba Enterococcus faecium - - - - - - R R - - - S - - - - - S S S S - - - - - - NaN

The dataset includes 28 different antibiotics. However, the resistance of each antibiotic has not been tested for all bacteria. The code is a unique identifier for each measured bacterium. The spectral measurements are saved in a '.txt' file with the code as the name. The spectra file paths are stored in the paths list.

In [40]:
raw_data.set_index("code", inplace=True)
raw_data.head()
Out[40]:
species Piperacillin-Tazobactam Meropenem Ciprofloxacin Cefepime Ceftazidime Amikacin Levofloxacin Imipenem Ceftriaxone Clindamycin Amoxicillin-Clavulanic acid Vancomycin Erythromycin Tetracycline Ertapenem Norfloxacin Nitrofurantoin Linezolid Teicoplanin Tigecycline Daptomycin Gentamicin Cefuroxime Oxacillin Rifampicin Fusidic acid Mupirocin Fosfomycin
code
74969164-613a-4455-ac8e-5666ee0dfade MIX!Streptococcus pneumoniae NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
e9adf43d-679b-497c-9849-1fa214838dd3 Staphylococcus epidermidis R R R R - - - R R S R S S R - - - S R S S R R R S R - NaN
926aea1e-27c2-410c-8f2a-ff00f2e9e585 Enterococcus faecalis - - - - - - S S - - - S - - - - - S S S - - - - - - - NaN
c110440a-17b1-4c35-964a-0870217ebe40 Staphylococcus epidermidis NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3755ec08-5951-46f9-b8eb-bcdccc2fd8ba Enterococcus faecium - - - - - - R R - - - S - - - - - S S S S - - - - - - NaN

Initial Data Analysis¶

Conduct an initial data analysis.

  • Present basic relevant quantities of the data that inform the reader about the dataset.
In [41]:
raw_data.agg(["count", "dtype", "unique"])
Out[41]:
species Piperacillin-Tazobactam Meropenem Ciprofloxacin Cefepime Ceftazidime Amikacin Levofloxacin Imipenem Ceftriaxone Clindamycin Amoxicillin-Clavulanic acid Vancomycin Erythromycin Tetracycline Ertapenem Norfloxacin Nitrofurantoin Linezolid Teicoplanin Tigecycline Daptomycin Gentamicin Cefuroxime Oxacillin Rifampicin Fusidic acid Mupirocin Fosfomycin
count 132286 48868 41233 53959 48816 48986 43129 39764 48228 48920 40952 51472 44033 41775 42334 45756 40473 41108 43123 39381 42367 39461 53906 41987 40634 42920 39823 39753 47245
dtype object object object object object object object object object object object object object object object object object object object object object object object object object object object object object
unique [MIX!Streptococcus pneumoniae, Staphylococcus ... [nan, R, -, S, I, R(1), S(1), S(2), I(1), S(1)... [nan, R, -, S, I, I(1), S(1), R(1), S(1), S(2)... [nan, R, -, S, I, S(2), R(1), S(1), I(1), S(1)... [nan, R, -, S, I(1), S(1), R(1), S(1), I, R(1)... [nan, -, S, I, R, R(1), I(1), S(2), I(1), S(1)... [nan, -, S, I, I(1), S(1), R, S(2), R(1), I(1)... [nan, -, S, R, R(1), I(1), I, S(2), I(1), S(1)... [nan, R, S, -, I, R(1), S(1), S(2), I(1), S(1)... [nan, R, -, S, I, R(1), S(1), I(1), S(1), R(1)... [nan, S, -, R, R(1), S(1), I, I(1), S(1)] [nan, R, -, S, R(1), S(1), I] [nan, S, -, R, R(1), S(1)] [nan, S, -, R, R(1), S(1), I, I(1), S(1)] [nan, R, -, S, I, R(1), S(1), R(1), I(1)] [nan, -, S, I, R, I(1), S(1), R(1), S(1), R(1)... [nan, -, S, R, I, R(1), I(1), I(1), S(1), R(1)... [nan, -, S, R, I(1), S(1), I, R(1), S(1), R(1)... [nan, S, -, I, R(1), S(1), R] [nan, R, S, -, R(1), S(1), I] [nan, S, -, R, I, R(1), S(1)] [nan, S, -, R(1), S(1), I, R] [nan, R, -, S, R(1), S(1), I] [nan, R, -, S, R(1), S(1), I] [nan, R, -, S, R(1), S(1)] [nan, S, -, R, I, R(1), S(1), R(1), I(1)] [nan, R, -, S, R(1), S(1)] [nan, -, S, R, R(1), S(1), I] [nan, -, R, S]

The labels are very sparse, meaning that for each antibiotic more than half of the resistance measurements are missing. For this project, the missing values are neither imputed nor dropped. Rather, the following models are trained with the missing values, which are masked in the loss function.

Furthermore, the labels are encoded as R and I for resistance and S for sensitivity. However, there are many more encodings like S(1) or R(2) that have to be replaced during processing.

In [42]:
pd.read_csv(paths[0], sep=" ")
Out[42]:
bin_index binned_intensity
0 0 0.000288
1 1 0.000433
2 2 0.000165
3 3 0.000366
4 4 0.000182
... ... ...
5995 5995 0.000082
5996 5996 0.000062
5997 5997 0.000076
5998 5998 0.000093
5999 5999 0.000126

6000 rows × 2 columns

The mass spectra measurements are structured in .txt files with index and binned_intensity separated by a space.

In [43]:
random_indices = random.sample(range(len(paths)), 8)
# plot the first 8 examples
fig, ax = plt.subplots(2, 4, figsize=(20, 10))
for i, ind in enumerate(random_indices):
    sns.lineplot(
        x=pd.read_csv(paths[ind], sep=" ")["bin_index"].values,
        y=pd.read_csv(paths[ind], sep=" ")["binned_intensity"].values,
        ax=ax[i // 4][i % 4],
        label=raw_data.loc[paths[i].split("/")[-1][:-4]]["species"],
    )
No description has been provided for this image
In [89]:
random_codes = random.sample(list(raw_data[raw_data["species"] == "Staphylococcus aureus"].index), 12)
# find the corresponding paths
random_paths = []
for code in random_codes:
    try:
        random_paths.append([path for path in paths if code in path][0])
    except IndexError:
        print(f"No path found for code {code}")

# plot the first 8 examples
fig, ax = plt.subplots(2, 4, figsize=(20, 10))
for i, path in enumerate(random_paths[:8]):
    sns.lineplot(
        x=pd.read_csv(path, sep=" ")["bin_index"].values,
        y=pd.read_csv(path, sep=" ")["binned_intensity"].values,
        ax=ax[i // 4][i % 4],
        label=raw_data.loc[path.split("/")[-1][:-4]]["species"],
    )
    ax[i // 4][i % 4].set_title(raw_data.loc[path.split("/")[-1][:-4]]["species"])
    # ax[i // 4][i % 4].legend()
No description has been provided for this image

As can be seen above, even the mass spectra of the same species of bacteria can look very different. In addition, while bacteria of the same species are expected to have a high similarity in antibiotic resistance, they do not necessarily have the same resistance to antibiotics due to small genetic variations between strains.3 Therefore, classifying the species is not enough to identify antibiotic resistance.

For this reason, and because classifying the species would be a potential machine learning task on its own, this project will completely ignore the species and classify the antibiotic resistance directly from the mass spectra measurements.


  1. S. A. Suarez and A. C. Martiny, “Intraspecific variation in antibiotic resistance potential within E. coli,” Microbiol Spectr, vol. 12, no. 6, pp. e03162-23, Jun. 2024, doi: 10.1128/spectrum.03162-23.

Preprocessing¶

Preprocessing steps already performed by the creators of the dataset:4

Preprocessing Step Description
Variance stabilization Transforms intensity values to reduce heteroskedasticity, making variability more uniform.
Smoothing Reduces random noise by averaging nearby data points, clarifying true signal peaks.
Baseline removal Subtracts background or chemical noise to isolate meaningful ion signals.
Intensity calibration Adjusts signal intensities to correct technical variability across spectra or instruments.
Trimming Removes irrelevant m/z ranges to focus on regions of interest and reduce data complexity.

Preprocessing steps performed here:

  1. Replace labels values with 1 (resistance) and 0 (sensitivity) according to the official package5
  2. Select intersection between given antibiotic resistance labels and mass spectra measurements

Note: Intensity calibration makes sure that the intensity is the same between different instruments which standardizes the intensity values. Therefore, no further scaling is applied. New values can easily be prepared for inference by using the pipeline described here and implemented in the mentioned package.5



  1. C. Weis et al., “Direct antimicrobial resistance prediction from clinical MALDI-TOF mass spectra using machine learning,” Nat Med, vol. 28, no. 1, pp. 164–174, Jan. 2022, doi: 10.1038/s41591-021-01619-9.
  2. https://github.com/BorgwardtLab/maldi-learn
In [46]:
from src.dataset import BacteriaDataset
# Data is a Torch Dataset that loads the data from the paths and labels dataframe
data = BacteriaDataset(raw_data, paths)
num_labels = len(data.label_names)
In [47]:
data.df_labels.drop(columns=["code"]).agg(["count", "dtype", "unique", "mean"])
Out[47]:
Piperacillin-Tazobactam Meropenem Ciprofloxacin Cefepime Ceftazidime Amikacin Levofloxacin Imipenem Ceftriaxone Clindamycin Amoxicillin-Clavulanic acid Vancomycin Erythromycin Tetracycline Ertapenem Norfloxacin Nitrofurantoin Linezolid Teicoplanin Tigecycline Daptomycin Gentamicin Cefuroxime Oxacillin Rifampicin Fusidic acid Mupirocin Fosfomycin
count 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775 128775
dtype int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64 int64
unique [-1, 1, 0] [-1, 1, 0] [-1, 1, 0] [-1, 1, 0] [-1, 0, 1] [-1, 0, 1] [-1, 0, 1] [-1, 1, 0] [-1, 1, 0] [-1, 0, 1] [-1, 1, 0] [-1, 0, 1] [-1, 0, 1] [-1, 1, 0] [-1, 0, 1] [-1, 0, 1] [-1, 0, 1] [-1, 0, 1] [-1, 1, 0] [-1, 0, 1] [-1, 0, 1] [-1, 1, 0] [-1, 1, 0] [-1, 1, 0] [-1, 0, 1] [-1, 1, 0] [-1, 0, 1] [-1, 1, 0]
mean -0.638594 -0.707894 -0.569031 -0.640202 -0.755341 -0.820796 -0.794813 -0.636288 -0.644481 -0.855539 -0.598338 -0.836971 -0.844846 -0.864539 -0.824547 -0.926686 -0.952281 -0.867288 -0.930313 -0.87298 -0.901782 -0.769955 -0.844085 -0.8539 -0.874789 -0.877787 -0.954991 -0.885149

Exploratory Data Analysis¶

In [48]:
f, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(
    data.df_labels.drop(columns=["code"]).replace(-1, np.nan).corr(),
    cmap=sns.diverging_palette(220, 10, as_cmap=True),
    vmin=-1.0,
    vmax=1.0,
    square=True,
    ax=ax,
)
Out[48]:
<Axes: >
No description has been provided for this image

Some antibiotics have a high correlation with other antibiotics. This means that they work or don't work against many of the same bacteria. If two antibiotics are highly correlated, it means that having both does not really add any benefit over having just one.

Another thing to consider is that multiple highly correlated antibiotics can lead to overrepresentation in the learning of the model, because the model can potentially score multiple antibiotics correctly by learning only one pattern for all of them. Since the loss is designed to be an average of all the individual losses, this could lead to overrepresentation and it may be that more correlated antibiotics such as Oxacillin and Cefuroxime show better performance.

In [90]:
# plot distribution of labels
class_dist = (
    data.df_labels.drop(columns=["code"]).replace(-1, np.nan)
    / data.df_labels.drop(columns=["code"]).replace(-1, np.nan).count()
    * 100
)
p = class_dist.sum().plot(
    kind="bar",
    figsize=(20, 10),
    title="Class distribution per label",
    ylabel="Resistant bacteria in %",
    xlabel="Labels",
)
No description has been provided for this image

The class distribution varies greatly between different bacteria. Some have a very low percentage of resistance, such as Linezolid, which means that it is expected to be effective against most bacteria. However, for example, more than 40% of the bacteria measured are resistant to Oxacilin.

In [50]:
%%cache /Volumes/FESTPLATTE/DL_project_data/data_plot -r -s

X = np.array([x for x, _ in data])
X_mean = np.mean(X, axis=0)
X_std = np.std(X, axis=0)

fig, axes = plt.subplots(2, 1, figsize=(20, 10))

axes[0].plot(X_mean, label='Mean', color='blue')
axes[0].set_title('Mean of all samples per bin')
axes[0].set_xlabel('Bin index')
axes[0].set_ylabel('Intensity')
axes[0].legend()

axes[1].plot(X_std, label='Standard Deviation', color='orange')
axes[1].set_title('Standard Deviation of all samples per bin')
axes[1].legend()
axes[1].set_xlabel('Bin index')
axes[1].set_ylabel('Intensity')

plt.tight_layout()
plt.show()

del X_mean, X_std, X
No description has been provided for this image

Looking at the distribution of the data shows that the lower bin frequencies have much higher intensity on average, while the higher frequencies generally have very low values and low variance. Therefore, the relevant patterns may be in a smaller subset of frequency bins.

Baselines¶

Stratification:

Since standard stratification algorithms are designed for multi-class classification and not for multi-label classification, this project uses an algorithm from the skmultilearn library. It iteratively stratifies multi-label data into folds, trying to maintain a balanced representation with respect to the order-th label combination. 6,7


  1. K. Sechidis, G. Tsoumakas, and I. Vlahavas, “On the Stratification of Multi-label Data,” in Machine Learning and Knowledge Discovery in Databases, vol. 6913, D. Gunopulos, T. Hofmann, D. Malerba, and M. Vazirgiannis, Eds., in Lecture Notes in Computer Science, vol. 6913. , Berlin, Heidelberg: Springer Berlin Heidelberg, 2011, pp. 145–158. doi: 10.1007/978-3-642-23808-6_10.
  2. P. Szymański and T. Kajdanowicz, “A Network Perspective on Stratification of Multi-Label Data,” 2017, arXiv. doi: 10.48550/ARXIV.1704.08756.
In [51]:
from skmultilearn.model_selection.iterative_stratification import iterative_train_test_split, IterativeStratification


def make_stratified_split(indices, y, test_size=0.2, random_state=RANDOM_SEED):
    train_size = 1 - test_size
    mskf = IterativeStratification(
        n_splits=2, sample_distribution_per_fold=[TEST_SIZE, train_size], random_state=RANDOM_SEED
    )

    train_indices, test_indices = next(mskf.split(indices, y))

    return train_indices, test_indices
In [ ]:
%%cache /Volumes/FESTPLATTE/DL_project_data/indices.pkl train_val_indices test_indices -r -s
from sklearn.dummy import DummyClassifier
from sklearn.svm import SVC

y = data.df_labels.values
indices = np.arange(len(data))
train_val_indices, test_indices = make_stratified_split(indices, y, test_size=TEST_SIZE, random_state=RANDOM_SEED)
In [53]:
train_val_dataset = BacteriaDataset(raw_data, paths, train_val_indices)
test_dataset = BacteriaDataset(raw_data, paths, test_indices)

Metrics¶

Metric selection presents several challenges:

  • Multi-label aspect
  • Unbalanced classes
  • Missing values

The multi-label aspect is handled by calculating the metrics for each label separately and then taking the average of all labels. This ensures that the performance of all labels is evaluated with equal weight. Furthermore, missing values can easily be disregarded in the computation of the metric for every label individually.

To account for unbalanced classes, balanced accuracy and area under the receiver operating characteristic (AUROC) are chosen as the main metrics.

AUROC provides an aggregated score across all thresholds that can be informative. It is widely used in binary classification. AUPRC is another metric that is widely used especially in medical applications when positive instances are much rarer than negative ones, which is the case for at least some of the antibiotics as shown earlier. However, the notion of its superiority over AUROC in unbalanced datasets has been questioned, and it is suggested that it may even be misleading.8

For this reason, in this project, AUROC is used for evaluation instead of AUPRC as a complement for balanced accuracy that measures performance across thresholds. Additionally, the metric allows for comparability with other contributions in the field, as it is commonly used. 9


  1. M. B. A. McDermott, H. Zhang, L. H. Hansen, G. Angelotti, and J. Gallifant, “A Closer Look at AUROC and AUPRC under Class Imbalance,” Jan. 13, 2025, arXiv: arXiv:2401.06091. doi: 10.48550/arXiv.2401.06091.
  2. L. S. Santiago, A. Guerrero-López, C. Sevilla-Salcedo, D. Rodríguez-Temporal, B. Rodríguez-Sánchez, and V. Gómez-Verdejo, “Machine Learning applied to MALDI-TOF data in a clinical setting: a systematic review,” Jan. 28, 2025. doi: 10.1101/2025.01.25.634879.

The strategy for the simple heuristic baseline is to choose the most frequent class for each label. Below is the implementation of a class for a classifier that follows this strategy.

In [56]:
from scipy import stats
from src.metrics import MultilabelMetricWithMissing
from src.dummy import DummyMultiLabel
from src.evaluation import evaluate_model
In [57]:
%%cache /Volumes/FESTPLATTE/DL_project_data/baseline_data.pkl X_train, X_test, y_train, y_test -r -s

# Retrieve the training data from the training dataset
X_train, y_train = zip(*[(X.detach().numpy(), y.detach().numpy()) for X, y in train_val_dataset])
X_train = np.array(X_train)
y_train = np.array(y_train)
print(f"X_train shape: {X_train.shape}, y_train shape: {y_train.shape}")

X_test, y_test = zip(*[(X.detach().numpy(), y.detach().numpy()) for X, y in test_dataset])
X_test = np.array(X_test)
y_test = np.array(y_test)
print(f"X_test shape: {X_test.shape}, y_test shape: {y_test.shape}")
X_train shape: (103586, 6000), y_train shape: (103586, 28)
X_test shape: (25189, 6000), y_test shape: (25189, 28)
In [58]:
dummy_model = DummyMultiLabel(data.label_names)
dummy_model.fit(X_train, y_train)
Most frequent label for all labels:                                0
Piperacillin-Tazobactam      0.0
Meropenem                    0.0
Ciprofloxacin                0.0
Cefepime                     0.0
Ceftazidime                  0.0
Amikacin                     0.0
Levofloxacin                 0.0
Imipenem                     0.0
Ceftriaxone                  0.0
Clindamycin                  0.0
Amoxicillin-Clavulanic acid  0.0
Vancomycin                   0.0
Erythromycin                 0.0
Tetracycline                 0.0
Ertapenem                    0.0
Norfloxacin                  0.0
Nitrofurantoin               0.0
Linezolid                    0.0
Teicoplanin                  0.0
Tigecycline                  0.0
Daptomycin                   0.0
Gentamicin                   0.0
Cefuroxime                   0.0
Oxacillin                    0.0
Rifampicin                   0.0
Fusidic acid                 0.0
Mupirocin                    0.0
Fosfomycin                   0.0

The simple heuristic baseline predicts 0 for all labels because it is the most frequent class for all of them.

In [59]:
results = []
y_pred = dummy_model.predict(X_test)
dummy_aurocs, dummy_accs = evaluate_model(y_test, y_pred, y_pred)

results.append(["dummy", "auroc", "test", np.nanmean(dummy_aurocs)])
results.append(["dummy", "acc", "test", np.nanmean(dummy_accs)])

y_pred = dummy_model.predict(X_train)
dummy_aurocs, dummy_accs = evaluate_model(y_train, y_pred, y_pred)

results.append(["dummy", "auroc", "train", np.nanmean(dummy_aurocs)])
results.append(["dummy", "bacc", "train", np.nanmean(dummy_accs)])
Multilabel balanced accuracy: 50.00%
Multilabel AUROC: 50.00%

Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.
Multilabel balanced accuracy: 50.00%
Multilabel AUROC: 50.00%

Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.
In [60]:
%%cache /Volumes/FESTPLATTE/DL_project_data/rf.pkl -r -s
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(random_state=RANDOM_SEED)
multi_target_forest = MultiOutputClassifier(forest, n_jobs=NUM_WORKERS)
y_pred = multi_target_forest.fit(X_train, y_train).predict(X_test)
RF_aurocs,  RF_accs = evaluate_model(y_test, y_pred, y_pred)

start_time = time.time()

results.append(['RandomForest', 'auroc','test', np.nanmean(RF_aurocs)])
results.append(['RandomForest', 'bacc', 'test', np.nanmean(RF_accs)])

y_pred = multi_target_forest.predict(X_train)
RF_aurocs, RF_accs = evaluate_model(y_train, y_pred, y_pred)

results.append(['RandomForest', 'auroc','train', np.nanmean(RF_aurocs)])
results.append(['RandomForest', 'bacc', 'train', np.nanmean(RF_accs)])

results_df = pd.DataFrame(results).T
results_df.columns = ['model', 'metric','mode', ] + data.label_names.tolist()
results_df.to_csv('results_machine_learning.csv', index=False)

results = pd.DataFrame(results, columns=['model', 'metric','mode', 'score'])
results.to_csv('results_machine_learning.csv', index=False)
print(f"Total training time: {(time.time() - start_time) / 60:.2f} min")
Multilabel balanced accuracy: 26.42%
Multilabel AUROC: 40.49%
Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.

Multilabel balanced accuracy: 99.93%
Multilabel AUROC: 99.85%
Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.

Total training time:  1399.57 min
In [61]:
del X_train, X_test, y_train, y_test  # clear memory

Deep Learning Experiments¶

In [ ]:
%%cache /Volumes/FESTPLATTE/DL_project_data/dl_indices.pkl train_indices val_indices -r -s

# perform another stratified split for the training and validation set
y_train_val = data.df_labels.drop(columns=['code']).iloc[train_val_indices].replace(-1, np.nan)
train_indices, val_indices = make_stratified_split(train_val_indices,y_train_val, test_size=VALIDATION_RATIO, random_state=RANDOM_SEED)
In [65]:
# define datasets
val_dataset = BacteriaDataset(raw_data, paths, val_indices)
train_dataset = BacteriaDataset(raw_data, paths, train_indices)

# define samplers
train_sampler = SubsetRandomSampler(list(range(len(train_dataset))))
val_sampler = SubsetRandomSampler(list(range(len(val_dataset))))

# define dataloaders
valid_loader = DataLoader(
    dataset=val_dataset, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, shuffle=False, sampler=val_sampler
)

train_loader = DataLoader(
    dataset=train_dataset, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, drop_last=True, sampler=train_sampler
)

test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, shuffle=False)

Models¶

The two models tested are a multi-layer perceptron (MLP) and a convolutional neural network (CNN) with residual connections. The details and design choices are explained later in this notebook.

MLP¶

I chose the Multi-Layer Perceptron because it has shown good results in similar applications.10 Furthermore, the architecture can capture complex non-linear patterns, which is probably necessary for this kind of task. The architecture consists of 5 layers, with the number of neurons per layer decreasing from 2048 to the output dimensionality. Therefore, the amount of information that can be retained is reduced at each layer. The total number of trainable parameters is 14,982,300, which is much smaller than the dimensionality of the training data ($6000 \times 88380 = 530,280,000$) and hopefully a good trade-off between bias and variance.


  1. L. S. Santiago, A. Guerrero-López, C. Sevilla-Salcedo, D. Rodríguez-Temporal, B. Rodríguez-Sánchez, and V. Gómez-Verdejo, “Machine Learning applied to MALDI-TOF data in a clinical setting: a systematic review,” Jan. 28, 2025. doi: 10.1101/2025.01.25.634879.
In [66]:
import torchsummary
from src.models import MLP

# Initialize the models
input_dim = 6000
output_dim = len(data.label_names)
mlp = MLP(input_dim, output_dim)
torchsummary.summary(mlp, (input_dim,))
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Linear-1                 [-1, 2048]      12,290,048
            Linear-2                 [-1, 1024]       2,098,176
            Linear-3                  [-1, 512]         524,800
            Linear-4                  [-1, 128]          65,664
            Linear-5                   [-1, 28]           3,612
================================================================
Total params: 14,982,300
Trainable params: 14,982,300
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.02
Forward/backward pass size (MB): 0.03
Params size (MB): 57.15
Estimated Total Size (MB): 57.20
----------------------------------------------------------------

Residual CNN¶

Convolutional Neural Networks are good at recognizing complex patterns in data and are especially good at extracting features from high-dimensional data. CNNs were originally developed for computer vision tasks. The task at hand shares some characteristics with image data. For example, nearby image pixels are statistically related, and so are nearby bins in this task. Furthermore, the pattern may differ from the exact location of the bins, which is also similar to image data. This suggests its suitability for this task.

The residual connections are implemented because they showed superior performance in deep convolutional neural networks.11 The original implementation had an average pooling layer after the residual block and just before the final fully connected classifier. However, in preliminary tests, this showed very poor performance. This could be due to the limited network depth and complexity, which is mainly limited by computational power. However, due to the poor performance of average pooling before the classifier, the model presented here simply flattens the convolutional layer with its channels.

The cell below implements the architecture. The commented lines are the originally designed implementation, which was reduced to excessive runtimes and, in the case of average pooling, poor performance.


  1. K. He, X. Zhang, S. Ren, and J. Sun, “Deep Residual Learning for Image Recognition,” Dec. 10, 2015, arXiv: arXiv:1512.03385. doi: 10.48550/arXiv.1512.03385.
In [67]:
from src.models import MassSpecResNet1D

cnn = MassSpecResNet1D(input_dim, output_dim)
torchsummary.summary(cnn, (input_dim,))
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv1d-1             [-1, 32, 6000]             192
       BatchNorm1d-2             [-1, 32, 6000]              64
              ReLU-3             [-1, 32, 6000]               0
            Conv1d-4             [-1, 64, 3000]          10,304
       BatchNorm1d-5             [-1, 64, 3000]             128
            Conv1d-6             [-1, 64, 3000]           2,112
       BatchNorm1d-7             [-1, 64, 3000]             128
              ReLU-8             [-1, 64, 3000]               0
   ResidualBlock1D-9             [-1, 64, 3000]               0
           Conv1d-10             [-1, 32, 1500]           6,176
      BatchNorm1d-11             [-1, 32, 1500]              64
           Conv1d-12             [-1, 32, 1500]           2,080
      BatchNorm1d-13             [-1, 32, 1500]              64
             ReLU-14             [-1, 32, 1500]               0
  ResidualBlock1D-15             [-1, 32, 1500]               0
           Conv1d-16               [-1, 4, 750]             388
      BatchNorm1d-17               [-1, 4, 750]               8
           Conv1d-18               [-1, 4, 750]             132
      BatchNorm1d-19               [-1, 4, 750]               8
             ReLU-20               [-1, 4, 750]               0
  ResidualBlock1D-21               [-1, 4, 750]               0
          Flatten-22                 [-1, 3000]               0
           Linear-23                  [-1, 256]         768,256
             ReLU-24                  [-1, 256]               0
          Dropout-25                  [-1, 256]               0
           Linear-26                   [-1, 64]          16,448
             ReLU-27                   [-1, 64]               0
           Linear-28                   [-1, 28]           1,820
================================================================
Total params: 808,372
Trainable params: 808,372
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.02
Forward/backward pass size (MB): 15.55
Params size (MB): 3.08
Estimated Total Size (MB): 18.65
----------------------------------------------------------------

Loss function¶

The Loss function is an adaption of Binary Cross Entropy (BCE) loss which is the default choice for multi-label classification. Essentially, for n labels, the BCE loss decomposes the multi-label classification task into n binary classification tasks.12

However, this framework struggles with unbalanced classes. A common strategy to deal with this problem is to assign weights based on class frequencies.13 This is also the strategy followed in this project for both model architectures.

Another problem with this particular task is the large number of missing labels. To solve this problem, a mask is created from the target values that is zero for all missing labels. Then, the unreduced BCE loss is calculated, multiplied by the mask, and averaged. This essentially ignores the missing values in the loss calculation.14


  1. T. Kobayashi, "Two-Way Multi-Label Loss," 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), Vancouver, BC, Canada, 2023, pp. 7476-7485, doi: 10.1109/CVPR52729.2023.00722.
  2. Khoi Pham, Kushal Kafle, Zhe Lin, Zhihong Ding, Scott Cohen, Quan Tran, and Abhinav Shrivastava. Learning to predict visual attributes in the wild. In CVPR, pages 13018– 13028, 2021.
  3. https://discuss.pytorch.org/t/loss-function-for-multi-label-classification-with-missing-values/114346/2
In [69]:
from src.losses import masked_bce_with_logits_loss
# weights as inverse frequency
label_counts = train_dataset.df_labels.drop(columns=["code"]).replace(-1, np.nan).sum(axis=0)
weights_0 = label_counts.values / train_dataset.df_labels.drop(columns=["code"]).replace(-1, np.nan).count()
weights_1 = 1 - weights_0
weights = torch.tensor(list(zip(weights_0, weights_1)))

weights = (
    train_dataset.df_labels.drop(columns=["code"]).replace(-1, np.nan).count()
    - train_dataset.df_labels.drop(columns=["code"]).replace(-1, np.nan).sum(axis=0)
) / train_dataset.df_labels.drop(columns=["code"]).replace(-1, np.nan).sum(axis=0)
weights = torch.tensor(weights.values)
weights
Out[69]:
tensor([3.3667e+00, 4.7718e+00, 3.1059e+00, 3.3865e+00, 6.2712e+00, 1.7208e+01,
        4.1935e+00, 3.2403e+00, 2.6735e+00, 2.1837e+00, 1.5743e+00, 8.8156e+01,
        1.4591e+00, 2.2703e+00, 5.3440e+01, 5.8898e+00, 4.3851e+00, 8.8909e+02,
        3.9527e+01, 3.3624e+02, 1.0830e+02, 3.7402e+00, 1.3687e+00, 1.3780e+00,
        1.9592e+01, 2.1164e+00, 1.2579e+02, 6.8293e-01], dtype=torch.float64)

Training¶

Due to the long training time, the models are stored in checkpoints every 10 epochs. Furthermore, only the balanced accuracy is computed at each epoch, which is then used as a criterion for early stopping. The training process for all models is defined in a function with the following steps:

  1. define hyperparameters
  2. load checkpoint if available
  3. loop through each epoch
    1. calculate loss
    2. adjust weights
    3. compute metrics on validation/training data and write results to file
    4. check if early stopping criterion is met (validation balance accuracy has not improved in the last 20 epochs)
    5. store checkpoint every 10 epochs
    6. trigger garbage collection and empty cache to avoid memory accumulation across epochs
  4. store the weights of the final model

Experiment with learning rates¶

The following cells show the execution of the experiments with different learning rates for each model. The training was monitored using Tensorboard, so there is not much output here regarding the performance during training. The details of the training performance will be analyzed in the next section.

MLP with Learning Rate: 0.001¶

In [72]:
%%cache /Volumes/FESTPLATTE/DL_project_data/mlp_001.pkl -r -s

train_model(
    model=mlp,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    kind='MLP',
    weights = weights,
    learning_rate=0.001)
Early stopping at epoch: 39

Total Training Time: 282.64 min
Best Validation Epoch:  18

MLP with Learning Rate: 0.0005¶

In [73]:
%%cache /Volumes/FESTPLATTE/DL_project_data/mlp_0005.pkl -r -s
train_model(
    model=mlp,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    weights=weights,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    kind='MLP',
    learning_rate=0.0005)
Early stopping at epoch: 37

Total Training Time: 261.10 min
Best Validation Epoch:  16

MLP with Learning Rate: 0.0001¶

In [74]:
%%cache /Volumes/FESTPLATTE/DL_project_data/mlp_0001.pkl -r -s
train_model(
    model=mlp,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='MLP',
    learning_rate=0.0001)
Early stopping at epoch: 49

Total Training Time: 329.01 min
Best Validation Epoch:  28

MLP with Learning Rate: 0.00001¶

In [75]:
%%cache /Volumes/FESTPLATTE/DL_project_data/mlp_00001.pkl -r -s
train_model(
    model=mlp,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='MLP',
    checkpoint_dir='/Volumes/FESTPLATTE/DL_project_data/checkpoints',
    learning_rate=0.00001)
Early stopping at epoch: 95

Total Training Time: 639.80 min
Best Validation Epoch:  74

CNN with Learning Rate 0.001¶

In [76]:
%%cache /Volumes/FESTPLATTE/DL_project_data/cnn_001.pkl -r -s
train_model(
    model=cnn,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='CNN',
    learning_rate=0.001)
Early stopping at epoch: 42

Total Training Time: 596.79 min
Best Validation Epoch:  21

CNN with Learning Rate 0.0005¶

In [77]:
%%cache /Volumes/FESTPLATTE/DL_project_data/cnn_0005.pkl -r -s
train_model(
    model=cnn,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='CNN',
    learning_rate=0.0005)
Early stopping at epoch: 22

Total Training Time: 309.84 min
Best Validation Epoch:  1

CNN with Learning Rate 0.0001¶

In [78]:
%%cache /Volumes/FESTPLATTE/DL_project_data/cnn_0001.pkl -r -s
train_model(
    model=cnn,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='CNN',
    learning_rate=0.0001)
Early stopping at epoch: 31

Total Training Time: 425.85 min
Best Validation Epoch:  10

CNN with Learning Rate 0.00001¶

In [79]:
%%cache /Volumes/FESTPLATTE/DL_project_data/cnn_00001.pkl -r -s
train_model(
    model=cnn,
    num_epochs=NUM_EPOCHS,
    train_loader=train_loader,
    valid_loader=valid_loader,
    num_labels=num_labels, 
    weights=weights,
    kind='CNN',
    checkpoint_dir='/Volumes/FESTPLATTE/DL_project_data/checkpoints',
    learning_rate=0.00001)
Early stopping at epoch: 54

Total Training Time: 648.23 min
Best Validation Epoch:  33

Evaluation¶

To analyze the training, the Tensorboard logs are read into a Pandas dataframe using the tbparse library.

In [81]:
from tbparse import SummaryReader

logdir = "runs"
reader = SummaryReader(logdir, extra_columns=set(["dir_name"]))
results_dl = reader.scalars

results_dl["model"] = results_dl["dir_name"].str.split("/").str[0]
results_dl["learning_rate"] = "0." + results_dl["dir_name"].str.split("/").str[1]
results_dl["metric"] = [x[2] if len(x) > 2 else "loss" for x in results_dl["dir_name"].str.split("/")]
results_dl.drop(columns=["dir_name"], inplace=True)
results_dl.drop_duplicates(subset=["step", "tag", "model", "learning_rate", "metric"], keep="first", inplace=True)

Baselines¶

In [83]:
baseline_results = pd.read_csv(
    "results_machine_learning.csv"
)
baseline_results = (
    baseline_results.melt(
        id_vars=["model", "metric", "mode"],
        value_vars=baseline_results.columns[3:],
        var_name="label",
        value_name="value",
    )
    .drop(columns=["label"])
    .groupby(["model", "metric", "mode"])
    .mean()
    .reset_index()
    .sort_values(by=["value"], ascending=False)
)
baseline_results["value"] = round(baseline_results["value"] * 100, 2).astype(str) + "%"
baseline_results = baseline_results.pivot(
    index=["model", "mode"], columns="metric", values="value"
).reset_index()  # .sort_values(by=['value'], ascending=False)
baseline_results.rename(columns={"bacc": "Balanced Accuracy", "auroc": "AUROC"}, inplace=True)
baseline_results
Out[83]:
metric model mode AUROC Balanced Accuracy
0 RandomForest test 40.49% 26.42%
1 RandomForest train 99.85% 99.93%
2 dummy test 50.0% 50.0%
3 dummy train 50.0% 50.0%

The random forest baseline is overfitting a lot with an balanced accuracy and AUROC of over 0.99 on the training data and balanced accuracy of 0.26 on the test set meaning that it does not generalize at all with this hyperparameter configuration. It is even worse than the baseline of choosing the most frequent label.

Deep Learning¶

In [84]:
try:
    # load the results of the final models
    results_of_final_models = pd.read_csv(
        "results_deep_learning.csv"
    )
except FileNotFoundError:
    # compute the results of the final models for all final models
    results_of_final_models = []
    for lr in ["001", "0005", "0001", "00001"]:
        for kind in ["MLP", "CNN"]:
            weights = torch.load(f"model_{kind}_{lr}.pkl", weights_only=True)
            if kind == "MLP":
                model = MLP(input_dim, output_dim)
            else:
                model = MassSpecResNet1D(input_dim, output_dim)
            model.load_state_dict(weights)
            print(f"Loaded {kind} model with learning rate {lr}")
            model.eval()
            y, y_pred, y_proba = get_targets_and_predictions(model=model, data_loader=valid_loader)
            print(f"Evaluating {kind} model with learning rate {lr}. {len(y)} samples")
            test_aurocs, test_accs = evaluate_model(y, y_pred, y_proba)
            results_of_final_models.append([kind, "0." + lr, np.nanmean(test_aurocs), np.nanmean(test_accs)])

    results_of_final_models = pd.DataFrame(
        results_of_final_models, columns=["model", "learning_rate", "AUROC", "Balanced Accuracy"]
    )
    results_of_final_models.to_csv("results_deep_learning.csv", index=False)


results_of_final_models["learning_rate"] = results_of_final_models["learning_rate"].astype(str)
results_of_final_models["AUROC"] = round(results_of_final_models["AUROC"] * 100, 2).astype(str) + "%"
results_of_final_models["Balanced Accuracy"] = (
    round(results_of_final_models["Balanced Accuracy"] * 100, 2).astype(str) + "%"
)
pd.concat(
    [results_of_final_models, baseline_results[baseline_results["mode"] == "test"].drop(columns=["mode"])]
).sort_values(by=["Balanced Accuracy"], ascending=False)
Out[84]:
model learning_rate AUROC Balanced Accuracy
7 CNN 1e-05 89.55% 85.72%
5 CNN 0.0001 84.62% 80.15%
3 CNN 0.0005 87.38% 79.82%
0 MLP 0.001 84.92% 77.68%
1 CNN 0.001 83.79% 77.68%
2 MLP 0.0005 83.48% 77.12%
4 MLP 0.0001 82.12% 76.57%
6 MLP 1e-05 76.46% 69.43%
2 dummy NaN 50.0% 50.0%
0 RandomForest NaN 40.49% 26.42%

In general, the CNN models performed slightly better than the MLP models. The CNN architecture with a learning rate of 0.00001 had the best overall balanced accuracy and AUROC on the validation data. The best performance for the MLP model is achieved with 0.001, which also has the best AUROC. All models tested are much better than the baselines.

In [85]:
from src.visualization import plot_results, plot_confusion_matrix, plot_roc_curves
plot_results("bacc_avg", "Balanced Accuracy")
No description has been provided for this image

In both cases, there are strong signs of overfitting early on. Both the balanced accuracy and the AUROC of the train strongly outperform their validation counterparts from early on in training. This effect is particularly strong for the CNN model. Learning rates 0.001, 0.0005, and 0.0001 show very high instability in the validation metric, suggesting that generalization does not reliably improve with epochs. They may be passing through several local minima of the validation loss surface. However, the results of the 0.00001 learning rate appear to improve more slowly, but also more stably. Emphasizing the suggestion that 0.00001 is the best of the tested learning rates for the CNN model.

So, while for MLP a higher learning rate (0.001) gives the best results on the validation data, for CNN a very low learning rate (0.00001) gives the best performance and the most stable training.

Interpretation for future adjustments:
MLP: It might be worth considering reducing the number of neurons per layer. This would increase the bias of the model while decreasing the variance. This could potentially counteract overfitting.

CNN: One possible solution would be to reduce the size of the bottleneck between the CNN feature extraction and the final dense layers. This would force the model to be more selective about the features it extracts, giving it less room to overfit the training data.

In [86]:
plot_results("loss", "Training Loss")
No description has been provided for this image
In [ ]:
cnn_final = MassSpecResNet1D(6000, 28)
mlp_final = MLP(6000, 28)
weights = torch.load("model_CNN_00001.pkl", weights_only=True)
cnn_final.load_state_dict(weights)

mlp_final.load_state_dict(torch.load("model_mlp_001.pkl", weights_only=True))


from src.evaluation import evaluate_final_model
from src.utils import get_targets_and_predictions


# y_true_cnn, y_pred_cnn, y_proba_cnn = evaluate_final_model(cnn_final)
y_true_mlp, y_pred_mlp, y_proba_mlp = evaluate_final_model(mlp_final)

Considering that in practice there is only one sample to be processed at a time (one mass spectrum per patient), the inference for this would only be approximately $$t(n=1) \approx \frac{342s}{25189} \approx 0.0126s$$

All the training for all the different learning rates and model architectures: $$283min + 261min+329min+640min+597min+310min+426min+648min = 3494 min = 58 h$$

In [ ]:
# y_pred = torch.round(torch.tensor(y_score)).detach().numpy()
test_aurocs_cnn, test_accs_cnn = evaluate_model(y_true_cnn, y_pred_cnn, y_proba_cnn, print_results=True)
Multilabel balanced accuracy: 79.32%
Multilabel AUROC: 84.92%

Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.
In [ ]:
test_aurocs_mlp, test_accs_mlp = evaluate_model(y_true_mlp, y_pred_mlp, y_proba_mlp, print_results=True)
Multilabel balanced accuracy: 76.18%
Multilabel AUROC: 84.20%

Unable to compute metrics for the following number of labels: AUROC: 0, Balanced Accuracy: 0.

Both the MLP and the CNN show worse performance on the test set compared to the validation set. This could be due to the high inter-epoch fluctuations in the metrics.

In [ ]:
# plot roc curve
from sklearn.metrics import roc_curve, auc
from src.visualization import plot_curves



    # Add legend and labels
    plt.legend(loc="lower right")
    plt.title(f"{title} Curves")
    plt.xlabel("False Positive Rate")
    plt.ylabel("True Positive Rate")
    plt.show()


plot_curves(y_true_cnn, y_proba_cnn, "CNN: ROC", roc_curve)
No description has been provided for this image
In [ ]:
plot_curves(y_true_mlp, y_proba_mlp, "MLP: ROC", roc_curve)
No description has been provided for this image

Both CNN and MLP ROC curves show good results for all antibiotics except Fosfomycin and Muipirocin. Both show poor performance with Fosfomycin even below the random guessing baseline with an auroc of less than 0.5.

Linezolid seems to be the most different between the two models. The CNN achieves an AUROC of 1.0 for this antibiotic, while the MLP achieves only an AUROC of 0.59, which is only slightly better than random.

In [ ]:
from src.visualization import plot_per_antibiotic

test_results_cnn = pd.DataFrame({"anibiotic": data.label_names, "auroc": test_aurocs_cnn, "bacc": test_accs_cnn})
test_results.sort_values(by=["bacc"], ascending=False, inplace=True)

plot_per_antibiotic(test_results_cnn, "bacc", "CNN: Balanced Accuracy")
No description has been provided for this image
In [ ]:
test_results_mlp = pd.DataFrame({"anibiotic": data.label_names, "auroc": test_aurocs_mlp, "bacc": test_accs_mlp})
test_results_mlp.sort_values(by=["bacc"], ascending=False, inplace=True)

plot_per_antibiotic(test_results_mlp, "bacc", "MLP: Balanced Accuracy")
No description has been provided for this image

The balanced accuracy shows a very similar picture with poor performance for Mupirocin and Fosfomycin in both models and very good performance for Linezolid in the CNN and very poor performance in the MLP. Overall, the balanced accuracies vary widely between the different antibiotics, suggesting that the models learned some associations much better than others, or that the resistance patterns for some antibiotics are much easier to detect than for others.

Comparison to other Contributions¶

Since the CNN model is better than the MLP, only it will be used for the comparison. Most other methods focus on single species and a small subset of antibiotics. 15 This makes comparison difficult. However, in order to do a comparison I also selected a subset of the test data.


  1. *L. S. Santiago, A. Guerrero-López, C. Sevilla-Salcedo, D. Rodríguez-Temporal, B. Rodríguez-Sánchez, and V. Gómez-Verdejo, “Machine Learning applied to MALDI-TOF data in a clinical setting: a systematic review,” Jan. 28, 2025. doi: 10.1101/2025.01.25.634879.
In [ ]:
# y_test select E.coli, K. pneumoniae, S. aureus
# get list with indices grouped by species
species = np.unique(test_dataset.species.values)
# dict for species and indices
species_indices = {}

for s in species:
    indices = np.where(test_dataset.species == s)[0]
    species_indices[s] = indices

# run model on each species
species_results = {}
for s, indices in species_indices.items():
    y_s = y_true[indices]
    y_pred_s = y_pred[indices]
    y_score_s = y_score[indices]

    test_aurocs_s, test_accs_s = evaluate_model(y_s, y_pred_s, y_score_s, print_results=False)
    species_results[s] = {"auroc": test_aurocs_s, "bacc": test_accs_s, "count": len(indices)}
In [ ]:
species_results_list = []
for key, value in species_results.items():
    species_results_list.append(([key] + value["auroc"] + ["auroc"] + [value["count"]]))
    species_results_list.append(([key] + value["bacc"] + ["bacc"] + [value["count"]]))


species_results_df = pd.DataFrame(
    species_results_list, columns=["species"] + data.label_names.tolist() + ["metric"] + ["count"]
)
species_results_df[
    species_results_df["species"].isin(["Escherichia coli", "Klebsiella pneumoniae", "Staphylococcus aureus"])
]
species_results_df = species_results_df.melt(id_vars=["species", "metric"], var_name="antibiotic", value_name="value")
species_results_df = (
    species_results_df[
        species_results_df["species"].isin(["Escherichia coli", "Klebsiella pneumoniae", "Staphylococcus aureus"])
        & species_results_df["antibiotic"].isin(
            [
                "Ceftriaxone",
                "Ciprofloxacin",
                "Cefepime",
                "Tobramycin",
                "Piperacillin-Tazobactam",
                "Meropenem",
                "Oxacillin",
                "Fusidic acid",
            ]
        )
    ]
    .pivot(index=["species", "antibiotic"], columns="metric", values="value")
    .reset_index()
    .drop([3, 4, 5, 10, 12, 13, 14, 15, 18, 20])
)
species_results_df["auroc"] = species_results_df["auroc"].astype(float).round(2)
species_results_df["bacc"] = species_results_df["bacc"].astype(float).round(2)
species_results_df
Out[ ]:
metric species antibiotic auroc bacc
0 Escherichia coli Cefepime 0.84 0.74
1 Escherichia coli Ceftriaxone 0.78 0.67
2 Escherichia coli Ciprofloxacin 0.80 0.71
6 Escherichia coli Piperacillin-Tazobactam 0.71 0.54
7 Klebsiella pneumoniae Cefepime 0.83 0.72
8 Klebsiella pneumoniae Ceftriaxone 0.81 0.69
9 Klebsiella pneumoniae Ciprofloxacin 0.80 0.72
11 Klebsiella pneumoniae Meropenem 0.90 0.60
16 Staphylococcus aureus Ciprofloxacin 0.86 0.75
17 Staphylococcus aureus Fusidic acid 0.75 0.50
19 Staphylococcus aureus Oxacillin 0.86 0.66

The table below shows the results of a recently published deep learning methodology for the same task based. 16 The reason I chose this paper as a reference is that it uses a similar architecture (CNN but without residual connections) and is trained and evaluated on a raw subset of the same database.

Below are the final results of the model introduced in the paper. A green underline means that my best model was better than the best model in the paper while a red underline means that the best model proposed in the paper had a better performance. A blue line indicates that the performance was very similar.

fmicb-15-1361795-t002.jpg

As can be seen here, my final model outperformed some of the bacteria-antibiotic pairs and showed similar performance with quite some of the others. This is quite astonishing considering the model here was trained on a much larger set of bacteria-antibiotic pairs while the model in the paper was specifically build and trained on this specific subset of bacteria-antibiotic pairs. Furthermore, here the hyperparameter testing and model complexity tested was quite limited.

However, to really understand the differences in performance it would be necessary to train and evaluate both models on the exact same split and training procedure.


  1. X. A. López-Cortés, J. M. Manríquez-Troncoso, R. Hernández-García, and D. Peralta, “MSDeepAMR: antimicrobial resistance prediction based on deep neural networks and transfer learning,” Front. Microbiol., vol. 15, p. 1361795, Apr. 2024, doi: 10.3389/fmicb.2024.1361795.

Conclusions and Future Work¶

Summary¶

This notebook implements training and evaluation for antimicrobial resistance (AMR) prediction. The different model architectures benefited from different learning rates. While for the MLP the highest tested learning rate seemed most promising, the CNN had the best performance with the lowest tested learning rate. Training was time consuming, but could probably be reduced significantly by using better hardware. Inference, on the other hand, is very fast, especially considering that in practice inference is performed on one or a few mass spectrometers at a time.

Overall, the best model presented here strongly outperforms the baseline and shows performance comparable to state-of-the-art models for this task. This suggests that the methods used here are a valid starting point for further optimization and potentially the construction of the first baseline model for antimicrobial resistance prediction based on mass spectrometry data. There are many other data sets that could be used to further improve performance.

Recommended course of action¶

The model presented here can be used as an antibiotic recommender, giving the physician insight into potential antibiotic resistance. When a patient with a bacterial infection enters a doctor's office, the doctor could perform a mass spectrometry of the bacteria and get the predicted antibiotic resistances within minutes. These prediction probabilities can be used to help decide which antibiotic to prescribe to the patient.

Despite the already promising performance demonstrated here, there seems to be much more potential, suggesting the implementation of further training and optimization.

Pitfalls and Limitations¶

It is definitely not recommended to use the model presented here for predicting resistance to the antibiotics mupirocin and fosfomycin. Both models showed very poor performance. In general, it is recommended to consider the overall accuracy of each antibiotic when evaluating a new prediction. The certainty of a prediction can vary greatly between individual antibiotics.

Another limitation is that the output probabilities on which the decision is based do not directly reflect confidence and certainty, which may be misleading to physicians.

Future Work¶

  1. Overparameterized model: Another interesting thing to consider is to go in the other direction and build a model with many more neurons than the input dimensions. Such models have shown good results in the past, especially with noisy data, which is the case here. 17
  2. Autoencoder with Bayesian neural networks: Quantifying confidence is very important for medical applications, and again it is important that the probabilities of the model output are reliable. Bayesian neural networks (BNN) are one approach to quantifying confidence and uncertainty using the Bayes theorem. However, they are more computationally expensive and do not perform as well on large datasets.18 Therefore, I would suggest to first train an autoencoder that reduces the dimensionality and finds a denser representation. As shown in the beginning, especially in the higher frequency bins, many values are close to zero, suggesting that there could be a denser representation of the data. This reduced representation could be used as input to the BNN, which could be advantageous since it reduces complexity.
  3. Lime: Explainability is very important in medicine, so it may be interesting to use Lime to investigate which frequency bins the model used to make the decision for a particular resistance prediction. It may be that the relevant frequency bins are very different for different antibiotics.

Discussion¶

AUROC and validation loss were not computed during training to save time. However, it would have been nice to collect AUROC and validation loss values during training to get a more detailed view of how training progresses with epochs.

It would have been interesting to test larger learning rates for the MLP, since the best MLP model used the highest tested learning rate, and smaller learning rates for the CNN, since the best performing CNN used the smallest tested learning rate.

The random forest baseline would definitely have benefited from some hyperparameter tuning, as the default option heavily overfits the training data, sometimes making it worse than the baseline.

Due to computational and time constraints, the complexity of the CNN model has been reduced. However, residual connections are particularly relevant in deep neural networks. Due to the reduction in layers and complexity of the CNN model, the architecture is no longer very deep, which raises the question of whether it is even necessary to use residual connections in this case. Since each residual block has only one layer, it is doubtful whether the residual connections add any benefit at all.


  1. P. Nakkiran, G. Kaplun, Y. Bansal, T. Yang, B. Barak, and I. Sutskever, “Deep Double Descent: Where Bigger Models and More Data Hurt,” 2019, arXiv. doi: 10.48550/ARXIV.1912.02292.
  2. K. Bykov et al., “Explaining Bayesian Neural Networks,” 2021, arXiv. doi: 10.48550/ARXIV.2108.10346.