Nkululeko: feature scaling

As described in this previous post, features scaling can be quite important in machine learning.

With nkululeko since version 0.97 you have a multitude if scaling methods at hand.

You simply state in the config:

[FEATS]
scale = xxx

For xxx you specify the scaling methods are

  • standard: z-transformation (mean of 0 and std of 1) based on the training set
    • robust: robust scaler
  • speaker: like standard but based on individual speaker sets (also for the test)
  • bins: convert feature values into 0, .5 and 1 (for low, mid and high)
  • minmax: rescales the data set such that all feature values are in the range [0, 1]
  • maxabs: similar to MinMaxScaler except that the values are mapped across several ranges depending on whether negative OR positive values are present
  • normalizer: scales each sample (row) individually to have unit norm (e.g., L2 norm)
  • powertransformer: applies a power transformation to each feature to make the data more Gaussian-like in order to stabilize variance and minimize skewness
  • quantiletransformer: applies a non-linear transformation such that the probability density function of each feature will be mapped to a uniform or Gaussian distribution (range [0, 1])

Nkululeko: how to explicitly model linguistics

With nkululeko since version 0.96 you there are linguistic feature extractors, i.e. using the text of the spoḱen words as input.

Of course you can combine them with acoustic features and use any fitting model architecture with it.

[EXP]
# optional: language for linguistics
language = de

[DATA]
data = ../mydata
# the linguistic feature extractors require a column named "text"
# example, perhaps not needed!
data.col_names = {"transcription":"text"}

[FEAT]
# combine linguistic bert features with acoustic open smile features
type = ['bert', 'os']

[MODEL]
type = xgb

Nkululeko: how to use train/dev/test splits

Supervised machine learning operates as follows: during the training phase, a learning algorithm is adapted to a training dataset, producing a trained model, which is then used to make predictions on a test set during the inference phase.

One potential issue with this approach is that, for sufficiently complex models, they may simply memorise all items in the training set rather than learning a generalised distinction based on an underlying process, such as emotional expression or speaker age. This means that while the model performs well on the training data, it fails to generalise to new data—a phenomenon known as overfitting.

To mitigate this, the model's hyperparameters are optimised using a held-out evaluation set that is not used during training. One particularly important hyperparameter is the number of epochs—that is, the number of times the entire training set is processed. Typically, to prevent overfitting, training is halted when performance on the evaluation set begins to decline, a technique known as early stopping. The model that performs best on the evaluation data is then selected.

However, this approach introduces a new problem: the model may (and most likely has) now overfitted to the evaluation data. This is why a third dataset is necessary for final testing—one that has not been used at any stage of model development.

The evaluation set is often referred to as the dev set (short for development set). Consequently, Nkululeko now provides support for three distinct data splits: train, dev, and test.

Here is an example how you would do this with emoDB (the distribution has no predefined splits for train, dev and test)

[EXP]
root = ./experiments/emodb_3split/
name = results
epochs = 100
traindevtest = True
[DATA]
databases = ['emodb']
emodb = ./data/emodb/emodb
emodb.split_strategy = speaker_split
labels = ["neutral", "sadness", "happiness"]
target = emotion
[FEATS]
type = ['os']
[MODEL]
type = mlp
layers = {'l1':100, 'l2':16}
patience = 10
[PLOT]
best_model = True
epoch_progression = True

You trigger the handling of three splits with

traindevtest = True

and the rest happens in this case automatically, the results are then shown for

best model based on development sets:

best model for dev set, but evaluated on test set:

and the last model, evaluated on the dev set:

In this case, you see that the 62nd epoch performed like the 52nd for the dev set. But, this best model evaluated on the test set, drops by more than 20 % average recall, which is a more stable value for the general performance of this model (this is only a toy example with 4 speakers in the training, and 2 each for dev and test set.)

Nkululeko: predict speaker id

With nkululeko since version 0.93.0 the pyannote segmentation package is interfaced (as an alternative to silero)

There are two modules that you can use for this:

  • SEGMENT
  • PREDICT

The (huge) difference is, that the SEGMENT module looks at each file in the input data and looks for speakers per file (can be only one large file), while the PREDICT module concatenates all input data and looks for different speakers in the whole database.

In any case best run it on a GPU, as CPU will be very slow (and there is no progress bar).

Segment module

If you specify the method in [SEGMENT] section and the hf_token (needed for the pyannote model) in the [MODEL] section

[SEGMENT]
method = pyannote
segment_target = _segmented
sample_selection = all
[MODEL]
hf_token = <my hugging face token>

your resulting segmentations will have predicted speaker id attachched.. Be aware that this is really slow on CPU, so best run on GPU and declare so in the [MODEL] section:

[MODEL]
hf_token = <my hugging face token>
device=gpu # or cuda:0

As a result a new plot would appear in the image folder: the distribution of speakers that were found, e.g. like this:

Predict module

Simply select speaker as the prediction target:

[PREDICT]
targets = ["speaker"]

Generally, the PREDICT module is described here

Nkululeko: ensemble learners with late fusion

With nkululeko since version 0.88.0 you can combine experiment results and report on the outcome, by using the ensemble module.

For example, you would like to know if the combination of expert features and learned embeddings works better than one of those. You could then do

python -m nkululeko.ensemble \
--method max_class \
tests/exp_emodb_praat_xgb.ini \
tests/exp_emodb_ast_xgb.ini \
tests/exp_emodb_wav2vec_xgb.in

(all in one line)
and would then get the results for a majority voting of the three results for Praat, AST and Wav2vec2 features.

Other methods are mean, max, sum, max_class, uncertainty_threshold, uncertainty_weighted, confidence_weighted:

  • majority_voting: The modality function for classification: predict the category that most classifiers agree on.
  • mean: For classification: compute the arithmetic mean of probabilities from all predictors for each labels, use highest probability to infer the label.
  • max: For classification: use the maximum value of probabilities from all predictors for each labels, use highest probability to infer the label.
  • sum: For classification: use the sum of probabilities from all predictors for each labels, use highest probability to infer the label.
  • max_class: For classification: compare the highest probabilities of all models across classes (instead of same class as in max_ensemble) and return the highest probability and the class
  • uncertainty_threshold: For classification: predict the class with the lowest uncertainty if lower than a threshold (default to 1.0, meaning no threshold), else calculate the mean of uncertainties for all models per class and predict the lowest.
  • uncertainty_weighted: For classification: weigh each class with the inverse of its uncertainty (1/uncertainty), normalize the weights per model, then multiply each class model probability with their normalized weights and use the maximum one to infer the label.
  • confidence_weighted: Weighted ensemble based on confidence (1-uncertainty), normalized for all samples per model. Like before, but use confidence (instead of inverse of uncertainty) as weights.

Nkululeko: export acoustic features

With nkululeko since version 0.85.0 the acoustic features for the test and the train (aka dev) set are exported to the project store.

If you specify the store_format:

[FEATS]
store_format = csv

they will be exported to CSV (comma separated value) files, else PKL (readable by python pickle module).
I.e. you store should then after execution of any nkululeko module that computes features the two files:

  • feats_test.csv
  • feats_train.csv

If you specified scaling the features:

[FEATS]
scale = standard # or speaker

you will have two additional files with features:

  • feats_test_scaled.csv
  • feats_train_scaled..csv

In contrast to the other feature stores, these contain the exact features that are used for training or feature importance exploration, so they might be combined from different feature types and selected via the features value. An example:

[FEATS]
type = ['praat', 'os']
features = ['speechrate_nsyll_dur', 'F0semitoneFrom27.5Hz_sma3nz_amean']
scale = standard
store_format = csv

results in the following feats_test.csv:

file,start,end,speechrate_nsyll_dur,F0semitoneFrom27.5Hz_sma3nz_amean
./data/emodb/emodb/wav/11b03Wb.wav,0 days,0 days 00:00:05.213500,4.028004219813945,34.42206
./data/emodb/emodb/wav/16b10Td.wav,0 days,0 days 00:00:03.934187500,3.0501850763340586,31.227554

....

Nkululeko: how to finetune a transformer model

Nkululeko Transformer Finetuning Guide

Overview

Starting with version 0.85.0, Nkululeko enables finetuning of pretrained transformer models using Hugging Face, with optional publication to their hub.

Finetuning vs. Normal Model Training

In normal Nkululeko training, [FEATS] extracts a fixed numeric feature vector for each sample once (e.g. openSMILE, wav2vec2 embeddings), and [MODEL] (e.g. svm, xgb, mlp, cnn) fits a classifier or regressor on top of those static features — the feature extractor itself never changes. Finetuning instead treats the pretrained transformer as the model itself: its own weights are updated directly on the raw audio via backpropagation, jointly adjusting the acoustic representation and the prediction head for your specific task.

Basic Configuration

To enable finetuning, set the MODEL type and leave acoustic features empty:

[FEATS]
type = []
[MODEL]
type = finetune

The system handles acoustic processing through CNN layers in the transformer, pooling frames for utterances up to 8 seconds by default.

Model Selection

The default base model is from Facebook (wav2vec2-large-robust-ft-swbd-300h), but alternatives can be specified. Finetuning-specific settings go in their own [FINETUNE] section:

[MODEL]
type = finetune

[FINETUNE]
pretrained_model = microsoft/wavlm-base
max_duration = 10.5

Training Parameters

Configuration keys, set under [FINETUNE]:

  • learning_rate: Training rate (default: 0.0001)
  • batch_size: Samples per iteration (default: 8)
  • device: GPU/CPU specification — a bare GPU index (e.g. 0) or cpu; autodetects if unset
  • measure: Evaluation metric, regression only (default: ccc); classification always uses UAR
  • loss: Loss function (default: cross for classification, 1-ccc for regression)
  • max_duration: Maximum sample length in seconds (default: 8)
  • push_to_hub: Boolean for publishing to Hugging Face (default: False)
  • drop: Dropout applied in the classification/regression head (default: 0.1)
  • balancing: Training-set balancing algorithm: ros, smote, or adasyn (default: none/disabled - false, none, or an empty value all mean disabled)
  • class_weight: Weight the loss by inverse class frequency, classification only (default: False)
  • freeze_layers: Number of pretrained encoder layers to freeze, counted from the input side (default: 0, meaning the whole backbone finetunes). Useful for partial finetuning on small datasets or to save GPU memory.
  • num_layers: Total number of encoder layers to build the model with, truncating the pretrained architecture to a smaller one (default: empty/unset, meaning the pretrained model's full depth). Unlike freeze_layers, this actually removes layers rather than just freezing their weights — fewer parameters, faster inference, smaller checkpoint.

Nkululeko validates 0 <= freeze_layers < num_layers <= <pretrained model's layer count> (using the pretrained depth wherever num_layers is left unset), and fails fast with a clear error otherwise — e.g. a num_layers larger than the checkpoint provides, or a freeze_layers that would freeze the entire resulting backbone and leave nothing trainable.

[FINETUNE]
pretrained_model = microsoft/wavlm-large
num_layers = 6
freeze_layers = 2

freeze_layers and num_layers are only supported for the standard HuggingFace wav2vec2/WavLM/HuBERT backends; both are ignored (with a warning) for emotion2vec* pretrained models.

Output & Loss Functions

Results include the best model and Hugging Face logs compatible with TensorBoard. Loss functions default to weighted cross-entropy for classification and concordance correlation coefficient for regression tasks.

Split strategies with Nkululeko train module

Usually in machine learning, you train your predictor on a train set, tune meta-parameters on a dev (development or validation set ) and evaluate on a test set.
With nkululeko, you have the following possiblities to split your data automaticfally: in addition, this entry describes how to use train/dev/test scenarios

How to Split Your Data

This tutorial explains different data splitting strategies in Nkululeko for supervised machine learning experiments. Based on the blog post by Felix Burkhardt.

Why Split Data?

In supervised machine learning, you typically need three kinds of datasets:

  1. Train data: To teach the model the relation between data and labels
  2. Dev data (development): To tune meta-parameters of your model (e.g., number of neurons, batch size, learning rate)
  3. Test data: To evaluate your model ONCE at the end to check on generalization

All of this is to prevent overfitting on your train and/or dev data. If you've used your test data for a while, you might need to find a new set, as chances are high that you overfitted on your test during experiments.

Rules for Good Data Splits

  • Train and dev can be from the same set, but the test set is ideally from a different database
  • If you don't have much data: use an 80/20/20% split
  • If you have masses of data: use only so much dev and test that your population seems covered
  • If you have really little data: use k-fold cross-validation for train and dev, but the test set should still be separate

Split Strategies in Nkululeko

Nkululeko offers several split strategies configured via split_strategy in the [DATA] section:

1. Specified Split

Use predefined train and test files. Ideal when you have a standard benchmark dataset with official splits.

Configuration:

[DATA]
emodb.split_strategy = specified
emodb.test_tables = ['emotion.categories.test.gold_standard']
emodb.train_tables = ['emotion.categories.train.gold_standard']

Example: exp_emodb_split_specified.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_specified.ini

When to use:

  • You have official benchmark splits
  • You want reproducible comparisons with other research
  • Dataset provides predefined train/test files

2. Random Split

Randomly assign samples to train and test sets. Simple but doesn't guarantee speaker independence.

Configuration:

[DATA]
emodb.split_strategy = random
emodb.test_size = 20  # 20% for test

Example: exp_emodb_split_random.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_random.ini

When to use:

  • Quick experiments
  • Large datasets where speaker overlap is less critical
  • When speaker information is not available

Caution: May lead to speaker overlap between train and test, resulting in optimistic performance estimates.


3. Speaker Split

Ensures speakers in train and test are different (speaker-independent evaluation). Critical for real-world generalization.

Configuration:

[DATA]
emodb.split_strategy = speaker_split
emodb.test_size = 20  # 20% for test

Example: exp_emodb_split_speaker.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_speaker.ini

When to use:

  • Real-world deployment scenarios
  • You want to test generalization to unseen speakers
  • Gold standard for speaker-independent evaluation

Why it matters: Prevents the model from memorizing speaker characteristics, forcing it to learn genuine emotion patterns.


4. LOSO (Leave-One-Speaker-Out)

Cross-validation where each speaker is held out once as the test set. Tests generalization to every speaker.

Configuration:

[DATA]
emodb.split_strategy = speaker_split
emodb.test_size = 10  # Percentage for initial split

[MODEL]
logo = 10  # Number of speakers for LOSO cross-validation

Example: exp_emodb_split_loso.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_loso.ini

When to use:

  • Small datasets with few speakers
  • You want robust speaker-independent evaluation
  • You need per-speaker performance analysis

How it works:

  • Uses speaker_split strategy to ensure speaker independence
  • The logo parameter specifies the number of speakers (folds)
  • For EmoDB with 10 speakers, logo = 10 means each fold leaves one speaker out (LOSO)
  • Trains 10 models, each testing on a different speaker

Note: Computationally expensive for datasets with many speakers. The number specified in logo should match the number of speakers in your dataset.


5. LOGO (Leave-One-Group-Out)

Cross-validation on the training data by leaving out one group at a time. Used for meta-parameter tuning.

Configuration:

[DATA]
emodb.split_strategy = random  # First split train/test
emodb.test_size = 20

[MODEL]
logo = 4  # Leave-One-Group-Out with 4 groups

Example: exp_emodb_split_logo.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_logo.ini

When to use:

  • Tuning model hyperparameters
  • You want more robust validation than single train/dev split
  • Combined with another split strategy for train/test

6. K-Fold Cross-Validation

Splits training data into K folds and trains K models, using each fold as validation once.

Configuration:

[DATA]
emodb.split_strategy = random  # First split train/test
emodb.test_size = 20

[MODEL]
k_fold_cross = 5  # 5-fold cross-validation

Example: exp_emodb_split_kfold.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_kfold.ini

When to use:

  • Small to medium datasets
  • You want robust performance estimates
  • Comparing different models or feature sets

Common values: 5-fold or 10-fold


7. Column Split

Split by the values of an arbitrary column (e.g. recording location, session, or any other metadata) instead of by speaker or a random percentage. Useful when your train/test distinction is defined by something other than speaker identity, such as recording site or acquisition device.

Configuration:

[DATA]
emodb.columns = ["age", "gender"]  # the split column must be listed here, or it isn't loaded
emodb.split_strategy = column
emodb.split_column = gender
emodb.train_vals = ['male']
emodb.test_vals = ['female']

Example: exp_emodb_split_column.ini

Run:

python -m nkululeko.train --config examples/exp_emodb_split_column.ini

When to use:

  • Your train/test distinction comes from metadata other than speaker (location, session, recording device, ...)
  • You want to evaluate generalization across a specific, known confound (e.g. train on one recording site, test on another)

How it works:

  • split_column names the column to split on; train_vals/test_vals (also spelled train_values/test_values) list which of that column's values go to which split
  • For a train/dev/test experiment, also set dev_vals
  • Rows whose value is in none of the configured lists are excluded from every split
  • The value lists must be pairwise disjoint -- the same value can't be assigned to two splits (this is validated and raises an error if violated)

Note: the split column must already be loaded into the dataframe via DATA.*db_name*.columns -- this applies even to columns that feel "standard", like gender.


Exercise 1: Compare Split Strategies

Try all split methods with EmoDB using OpenSMILE features and XGBoost:

# 1. Specified split
python -m nkululeko.train --config examples/exp_emodb_split_specified.ini

# 2. Random split
python -m nkululeko.train --config examples/exp_emodb_split_random.ini

# 3. Speaker split
python -m nkululeko.train --config examples/exp_emodb_split_speaker.ini

# 4. LOSO
python -m nkululeko.train --config examples/exp_emodb_split_loso.ini

# 5. LOGO
python -m nkululeko.train --config examples/exp_emodb_split_logo.ini

# 6. 5-fold cross-validation
python -m nkululeko.train --config examples/exp_emodb_split_kfold.ini

# 7. Column split
python -m nkululeko.train --config examples/exp_emodb_split_column.ini

Question: Which split strategy gives the best performance? Why?

Expected findings:

  • Random split typically gives the highest performance (but least realistic)
  • Speaker split / LOSO give more conservative (realistic) performance
  • K-fold / LOGO provide robust estimates with confidence intervals

Exercise 2: Detecting Overfitting

Run a neural network experiment to visualize when overfitting starts:

Configuration: exp_emodb_split_overfitting.ini

python -m nkululeko.train --config examples/exp_emodb_split_overfitting.ini

This configuration:

  • Uses an MLP with layers {l1: 1024, l2: 64}
  • Trains for 200 epochs
  • Plots epoch progression and identifies the best model

What to look for:

  1. Open the epoch progression plot in examples/results/exp_emodb_split_overfitting/images/
  2. Find where training loss continues decreasing but validation loss starts increasing
  3. That's where overfitting begins!

Comparison Table

Split Strategy Speaker Independent Use Case Computational Cost Realism
Specified Depends on dataset Benchmark comparison Low Varies
Random ❌ No Quick experiments Low Low
Speaker Split ✅ Yes Real-world deployment Low High
LOSO ✅ Yes Small datasets, per-speaker analysis High Very High
LOGO Configurable Hyperparameter tuning Medium Medium
K-Fold Configurable Robust evaluation Medium-High Medium
Column Depends on column chosen Splitting by a known metadata confound (location, session, device, ...) Low Varies

Best Practices

For Small Datasets (< 1000 samples)

  1. Use k-fold cross-validation (k=5 or k=10) on train+dev
  2. Keep a separate test set that you evaluate ONLY ONCE
  3. Consider LOSO if you have < 20 speakers

For Medium Datasets (1000-10,000 samples)

  1. Use speaker split with 80/10/10 (train/dev/test)
  2. Ensure different speakers in each split
  3. Use k-fold on training data for hyperparameter tuning

For Large Datasets (> 10,000 samples)

  1. Simple random split or speaker split works well
  2. Dev and test sets can be smaller (e.g., 5% each)
  3. Focus on ensuring the test set covers the population diversity

General Tips

  • ✅ Always keep test data separate until final evaluation
  • ✅ Use speaker split for realistic performance estimates
  • ✅ Use cross-validation for robust hyperparameter tuning
  • ❌ Never tune on test data
  • ❌ Don't evaluate on test data multiple times (you'll overfit!)

Advanced: Balanced Splits

For imbalanced datasets, use stratified or balanced splits:

[DATA]
emodb.split_strategy = balanced
emodb.test_size = 20
# Stratify by multiple variables with weights
balance = {'emotion':2, 'age':1, 'gender':1}
age_bins = 2
size_diff_weight = 1

See exp_emodb_split.ini for a complete example.


References


Summary

Choosing the right split strategy is crucial for reliable machine learning experiments:

  • For benchmarking: Use specified splits
  • For real-world deployment: Use speaker split or LOSO
  • For quick experiments: Use random split
  • For small datasets: Use k-fold cross-validation
  • For hyperparameter tuning: Use LOGO or k-fold
  • For splitting by a known metadata confound: Use column split

Remember: Your test set performance is only meaningful if it represents the real-world scenario your model will face!