Skip to main content

maldi-tof-classifier

Version: 0.3.3

The maldi-tof-classifier package provides functionality for:

  • Reading MALDI-TOF spectra
  • Preprocessing spectral data
  • Machine learning based classification

It is designed for spectra generated by a Shimadzu 8030 MALDI-TOF mass spectrometer.

Source code: https://github.com/ofmk94/maldi-tof-classifier

License: MIT


Installation

Python 3.10 or later is required.

Install the package from PyPI:

pip install maldi-tof-classifier

Additionally, the R package MALDIquant must be installed on the system. It can usually be installed from within R with:

install.packages("MALDIquant")

Overview

This README consists of two parts:

  1. CLI tool usage
  2. Python API and typical workflows

The tool is a Python package, but foremost a CLI tool.

It is strongly recommended to work with peak data and the default PeakExtractor.

Example data for download is available under: https://github.com/ofmk94/maldi-tof-classifier-data


Part 1 - CLI Tool Usage

1.1 Required directory structure

The CLI tool requires the following directory structure:

data_train/
    A/
        sample1.csv
        sample2.csv
    B/
        sample3.csv

data_predict/
    unknown1.csv
    unknown2.csv

cli_files/
    config.yaml
  • data_train Contains subdirectories for the classes to be learned, for example A, B, C. The subdirectories may contain either .txt files with spectra or .csv files with peak data as produced by a Shimadzu 8030 MALDI-TOF mass spectrometer. This directory is for training only.

  • data_predict Contains files of the same type, either .txt full spectra or .csv peak data, to be classified. This directory is for prediction.

  • cli_files Contains the files necessary for the CLI setup and the files with results. It must contain config.yaml.

Training and prediction must use the same file type and the same extractor.


1.2 Output files

The following files are created inside cli_files during usage:

cli_files/pipeline.joblib
    created once the model with the classification pipeline is trained.

cli_files/training_performance.txt
    test-set performance of the trained classification pipeline
    includes accuracy, macro-averaged precision, macro-averaged recall,
    macro-averaged F1 score, and the confusion matrix.

cli_files/predictions.csv
    predictions on data_predict data.

1.3 CLI commands

There are two commands available:

Train the model:

mtc train

Predict on new data:

mtc predict

Both commands need to be executed in an environment with the directories described above.


1.4 Configuration via config.yaml

The setup for the training can be thoroughly defined through cli_files/config.yaml.

All parameters are optional. There are default values for everything, so providing settings is optional.


1.5 Extractor settings

1.5.1 extractor_cls

Type of extractor.

Options:

  • "PeakExtractor" for working with .csv files containing peak data
  • "FullSpectraExtractor" for full spectra .txt files

Default:

extractor_cls: "PeakExtractor"

This must be coherent between mtc train and mtc predict.

1.5.2 extractor_params

Additional optional parameters for PeakExtractor or FullSpectraExtractor.

Default:

extractor_params: null

These parameters are passed directly to the selected extractor constructor.

For PeakExtractor, the main parameters are:

  • snr_thresh default 3.0
  • rel_shift_tolerance default 0.002
  • min_peak_freq default 0.25

Example:

extractor_params:
    snr_thresh: 3.0
    rel_shift_tolerance: 0.002

For FullSpectraExtractor, the main parameters are:

  • use_mz_cutoff default false
  • mz_cutoff_mass default 20000.0

Example:

extractor_params:
    use_mz_cutoff: true
    mz_cutoff_mass: 20000.0

The dataclasses for file location and file parsing are advanced options and should generally not be set by the CLI user.


1.6 Scaling and dimensionality reduction

1.6.1 scaler_cls

Scaling object.

Available options from sklearn.preprocessing:

  • "StandardScaler"
  • "MinMaxScaler"

Optional.

Default:

scaler_cls: null

1.6.2 dim_reducer_cls

Optional dimensionality reduction.

Options:

  • "PCA" from sklearn.decomposition
  • "SVD" using sklearn.decomposition.TruncatedSVD

Default:

dim_reducer_cls: null

1.6.3 n_components

Number of components to use in optional dimensionality reduction.

Type:

  • int

Default:

n_components: 20

1.7 Classifier settings

1.7.1 classifier_cls

Classification model.

Available options:

  • sklearn models: LogisticRegression, LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis, PLSRegression as PLS-DA, SVC, RandomForestClassifier
  • xgboost model: XGBClassifier
  • special option: OPLS-DA, implemented using pyopls.OPLS, PLSRegression, and OneVsRestClassifier for multiclass classification.

Default:

classifier_cls: "RandomForestClassifier"

1.7.2 classifier_params

Optional parameters for the classifier.

Default:

classifier_params: null

These parameters are passed to the selected classifier. Only parameters valid for the selected classifier should be used here.

Examples:

classifier_params:
    n_estimators: 200
    max_depth: 10

or:

classifier_params:
    C: 1.0
    max_iter: 1000

For OPLS-DA, use pipeline prefixes:

  • opls__ for OPLS
  • pls__ for PLSRegression

Example:

classifier_cls: "OPLS-DA"
classifier_params:
  opls__n_components: 1
  pls__n_components: 2

For OPLS-DA, the separate scaler_cls, dim_reducer_cls, and top-level n_components settings are not applied. OPLS and PLS components can be configured through opls__n_components and pls__n_components in classifier_params.

Refer to the documentation of scikit-learn, xgboost, or pyopls for the full list of supported parameters.

1.8 Train/test split and balancing

1.8.1 test_size

Size of test set.

Type:

  • float

Default:

test_size: 0.25

1.8.2 oversampling

Whether simple oversampling should be performed for balancing training classes.

Type:

  • bool

Default:

oversampling: true

1.9 Notes

  • It is strongly recommended to work with peak data and the default PeakExtractor.
  • Training and prediction must use the same extractor and the same data format.
  • The advanced file parsing options are usually not needed for standard CLI usage.

Part 2 - Python API and typical workflows

2.1 Overview

The maldi-tof-classifier package provides functionality for:

  • Reading MALDI-TOF spectra
  • Preprocessing spectral data
  • Machine learning based classification

Source code: https://github.com/ofmk94/maldi-tof-classifier

Example data: https://github.com/ofmk94/maldi-tof-classifier-data

Docstrings contain more detailed information on parameters and behavior. This section illustrates typical usage.

The directory structure is the same as in Part 1.


2.2 Step 1 - Loading and preprocessing data

Recommended: peak data using PeakExtractor

from maldi_tof_classifier.extractors import PeakExtractor
from pathlib import Path
from sklearn.model_selection import train_test_split

TRAIN_DIR = Path(".") / "data_train"

extractor = PeakExtractor(snr_thresh=3.0)

peaks_dfs, class_labels = extractor.extract_train_data(TRAIN_DIR)

X_train, X_test, y_train, y_test = train_test_split(
    peaks_dfs, class_labels, test_size=config["test_size"]
)

X_train = extractor.transform_train_data(X_train)
X_test = extractor.transform_predict_data(X_test)

Alternative: full spectra using FullSpectraExtractor

from maldi_tof_classifier.extractors import FullSpectraExtractor

extractor = FullSpectraExtractor(use_mz_cutoff=True, mz_cutoff_mass=20000.0)

spectra, class_labels, spots = extractor.extract_train_data(TRAIN_DIR)

X_train, X_test, y_train, y_test = train_test_split(
    spectra, class_labels, test_size=config["test_size"]
)

2.3 Step 2 - Label encoding

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

y_train = le.fit_transform(y_train)
y_test = le.transform(y_test)

2.4 Step 3 - Handle class imbalance (optional)

from imblearn.over_sampling import RandomOverSampler

ros = RandomOverSampler()
X_train, y_train = ros.fit_resample(X_train, y_train)

2.5 Step 4 - Scaling (optional)

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()

X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

2.6 Step 5 - Dimensionality reduction (optional)

from sklearn.decomposition import PCA

pca = PCA(n_components=20)

X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)

2.7 Step 6 - Classification

RandomForestClassifier

from sklearn.ensemble import RandomForestClassifier

classifier = RandomForestClassifier()

classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

XGBClassifier

from xgboost import XGBClassifier

classifier = XGBClassifier()

classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)


OPLS-DA

Multiclass OPLS-DA is implemented using a one-vs-rest strategy. Each binary estimator applies an OPLS transformation followed by PLS regression.

from pyopls import OPLS
from sklearn.cross_decomposition import PLSRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import Pipeline

classifier = OneVsRestClassifier(
    Pipeline([
        ("opls", OPLS()),
        ("pls", PLSRegression()),
    ])
)

classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

2.8 Neural network models

Available in maldi_tof_classifier.nn:

  • LSTMClassifier

For neural networks, a train/validation/test split and one-hot encoding is typically used.

Split

from sklearn.model_selection import train_test_split

X_train, X_val_test, y_train, y_val_test = train_test_split(
    spectra,
    class_labels,
    test_size=0.3,
    stratify=class_labels
)

X_val, X_test, y_val, y_test = train_test_split(
    X_val_test,
    y_val_test,
    test_size=0.333,
    stratify=class_labels
)

Label encoding

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

y_train = le.fit_transform(y_train)
y_val = le.transform(y_val)
y_test = le.transform(y_test)

One-hot encoding

from tensorflow.keras.utils import to_categorical

n_classes = len(le.classes_)

y_train = to_categorical(y_train, n_classes)
y_val = to_categorical(y_val, n_classes)
y_test = to_categorical(y_test, n_classes)

Example

from maldi_tof_classifier.nn import LSTMClassifier

model = LSTMClassifier(X_train, y_train)

model.fit(
    X_train,
    y_train,
    epochs=20,
    validation_data=(X_val, y_val)
)

y_pred = model.predict(X_test)

2.9 Pipeline API

Steps 2.5–2.7 (Step 4–6) can be combined into a pipeline:

from maldi_tof_classifier.pipelines import generate_pipeline

Components

  • Scaler (optional)
  • Dimensionality Reduction (optional)
  • Classifier (required)

Parameters

  • classifier_cls Instantiable class of the classifier.

  • classifier_params Parameters passed to the classifier.

  • scaler_cls Optional scaler class.

  • dim_reducer_cls Optional dimensionality reduction class.

  • n_components Number of components for dimensionality reduction.

Example

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier

from maldi_tof_classifier.pipelines import generate_pipeline

pipeline = generate_pipeline(
    classifier_cls=RandomForestClassifier,
    classifier_params={"n_estimators": 100},
    scaler_cls=StandardScaler,
    dim_reducer_cls=PCA,
    n_components=20
)

pipeline.fit(X_train, y_train)

y_pred = pipeline.predict(X_test)

Author

Oliver Klein
oliver.klein@stud.hcw.ac.at
oliverfmklein@gmail.com


License

This project is licensed under the MIT License.

Copyright (c) 2026 Oliver Felix Matthias Klein (GitHub username: ofmk94)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Disclaimer

Disclaimer

This README was written based on the original draft, revised into English Markdown format, and completed with additional content with assistance from ChatGPT versions 5.3, 5.5, and 5.6.

No liability is assumed for the provided software or for the contents of this README.


Last edited: July 26th, 2026

No liability is assumed for the provided software or for the contents of this README.


Last edited: July 26th, 2026

Metadata

Release files for maldi-tof-classifier 0.3.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for maldi-tof-classifier 0.3.3
File Size Uploaded
maldi_tof_classifier-0.3.3.tar.gz 21.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for maldi-tof-classifier 0.3.3
File Interpreter ABI Platform
maldi_tof_classifier-0.3.3-py3-none-any.whl Python 3 none any Details

Total release size: 42.2 kB

Release files / maldi_tof_classifier-0.3.3.tar.gz

Download URL maldi_tof_classifier-0.3.3.tar.gz
Size 21.2 kB
Tags Source
SHA-256 checksum
How to use checksums
26b3f9f960cb3ad4140b7009386f4a3b540f4906641b2b550f812fef7de7b89e
BLAKE2b-256 checksum
How to use checksums
81aeed43b13846a506a0437ac0bb15fdbdd6739199f7f27c732eeb2d1713db79
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.12

Release files / maldi_tof_classifier-0.3.3-py3-none-any.whl

Download URL maldi_tof_classifier-0.3.3-py3-none-any.whl
Size 20.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
551711f57532a92fc1bbeb3d51c41f7045529aab4290381d7313ea6fb088d7a4
BLAKE2b-256 checksum
How to use checksums
625bf12481b6e0a6b2281ec08fe8b89cb91c54cb38c8cfe27c9a2213087f7f7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.12

Release history Release notifications | RSS feed

This release

0.3.3 This release

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page