Category Archives: Allgemein

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: 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.

Nkululeko: how to tweak the target variable for database comparison

Sometimes you want to compare two different databases that share a similar target variable, say, related to likability, but in a different scaling, say the one asked on a scale from 1 to 10 and the other used likert-scale from 1-7.

With nkululeko you can re-name labels, normalize the target values, and even inverse the polarity, for each databases.

In the following example there are two databases

[DATA]
databases = ['db1', 'db2']
db1.split_strategy = test
db1.scale = True
db2.colnames = {'non-attractive':'likability'}
db2.split_strategy = train
db2.scale = True
db2.reverse = True
db2.reverse.max = 10
target = likability
bins = [-1000, .2, 1000]
labels = ['less likable', 'more likable']

The one database db1 already has a likability label and just needs to be standard-normalized, the second one db2 has a related label non-attractive which needs to be renamed, inverted (based on a hypothetical maximum value of 10) and normalized.
Then, db1 can be used as test data and db2 as training.

Nkululeko: compare several databases

With nkululeko since version 0.77.7 there is a new interface named multidb which lets you compare several databases.

You can state their names in the [EXP] section and they will then be processed one after each other and against each other, the results are stored in a file called heatmap.png in the experiment folder.

!Mind YOU NEED TO OMIT THE PROJECT NAME!

nkululeko.multidb

Multidb module for database comparison

With nkululeko since version 0.77.7 there is a new interface named multidb, which lets you compare several databases.

You can state their names in the [EXP] section and they will then be processed one after each other and against each other; the results are stored in a file called heatmap.png in the experiment folder.

The heatmap includes an extra "mean (cross)" row and column: the mean performance across the other databases, excluding each database's own self-train/self-test (diagonal) result. If every single result in the run comes back as exactly 0.0 (usually caused by an empty train/test split for every database pair, or a saved model being reused against an unlabeled test set), no heatmap is written at all -- an error message is printed instead, since an all-zero matrix isn't a meaningful result to plot.

If an individual database pair fails (e.g. a split leaving train/test label sets that don't overlap), that pair is logged and left blank in the heatmap rather than aborting the whole run -- every other pair still gets computed and plotted.

Each database's acoustic features (extracted once per database, before any train/test split) are shared across every pair it appears in, in a _feat_cache folder under [EXP] root, instead of being re-extracted once per pair -- set DATA.no_reuse or FEATS.no_reuse to disable this and always extract fresh.

Here is an example of such an INI file

[EXP]
root = ./experiments/emodbs/
#  You don't need to give it a name, 
# this will be the combination 
# of the two databases: 
# traindb_vs_testdb
epochs = 1
databases = ['emodb', 'polish']
[DATA]
root_folders = ./experiments/emodbs/data_roots.ini
target = emotion
labels = ['neutral', 'happy', 'sad', 'angry']
[FEATS]
type = ['os']
[MODEL]
type = xgb

You can (but don't have to) state the specific dataset values in an external file like above.

[DATA]
emodb = ./data/emodb/emodb
emodb.split_strategy = specified
emodb.test_tables = ['emotion.categories.test.gold_standard']
emodb.train_tables = ['emotion.categories.train.gold_standard']
emodb.mapping = {'anger':'angry', 'happiness':'happy', 'sadness':'sad', 'neutral':'neutral'}
polish = ./data/polish_emo
polish.mapping = {'anger':'angry', 'joy':'happy', 'sadness':'sad', 'neutral':'neutral'}
polish.split_strategy = speaker_split
polish.test_size = 30

Finally, you can run the experiment with the following command:

python -m nkululeko.multidb --config my_conf.ini

or, equivalently, with the config file as a plain positional argument:

python -m nkululeko.multidb my_conf.ini

Here's a result with two databases:

Another example for combining dementianet and dementiabank:

[EXP]
root = ./results
name = exp_multidb_dementia
save = True

[DATA]
databases = ['dementianet_train', 'dementianet_val', 'dementianet_test', 'dementiabank_train', 'dementiabank_val', 'dementiabank_test']
; DementiaNet dataset
dementianet_train = ./data/dementianet/dementianet_train.csv
dementianet_train.type = csv
dementianet_train.absolute_path = False
dementianet_train.mapping = {'nodementia': 'control', 'dementia': 'dementia'}
dementianet_train.split_strategy = train
dementianet_val = ./data/dementianet/dementianet_val.csv
dementianet_val.type = csv
dementianet_val.absolute_path = False
dementianet_val.mapping = {'nodementia': 'control', 'dementia': 'dementia'}
dementianet_val.split_strategy = train
dementianet_test = ./data/dementianet/dementianet_test.csv
dementianet_test.type = csv
dementianet_test.absolute_path = False
dementianet_test.mapping = {'nodementia': 'control', 'dementia': 'dementia'}
dementianet_test.split_strategy = test
; DementiaBank dataset
dementiabank_train = ./data/dementiabank/dementiabank_train.csv
dementiabank_train.type = csv
dementiabank_train.absolute_path = False
dementiabank_train.mapping = {'control': 'control', 'dementia': 'dementia'}
dementiabank_train.split_strategy = train
dementiabank_val = ./data/dementiabank/dementiabank_val.csv
dementiabank_val.type = csv
dementiabank_val.absolute_path = False
dementiabank_val.mapping = {'control': 'control', 'dementia': 'dementia'}
dementiabank_val.split_strategy = train
dementiabank_test = ./data/dementiabank/dementiabank_test.csv
dementiabank_test.type = csv
dementiabank_test.absolute_path = False
dementiabank_test.mapping = {'control': 'control', 'dementia': 'dementia'}
dementiabank_test.split_strategy = test
target = dementia

[FEATS]
type = ['praat']
scale = speaker
balancing = ros

[EXPL]
feature_distributions = True
model = ['xgb']
permutation = True
max_feats = 15
sample_selection = all
shap = True
scatter = ['umap', 'pca']

[MODEL]
type = xgb
save = True
n_estimators = 100
max_depth = 6
learning_rate = 0.3
subsample = 1.0
n_jobs = 10

[RESAMPLE]
replace = True

[PLOT]
format = pdf

Leave-one-dataset-out (LODO) mode

Set EXP.lodo = True to switch multidb from the default N x N pairwise matrix to leave-one-dataset-out (LODO) cross-validation: for each database in databases, that database is held out as the fold's test set while every other database in the list is pooled together for training, rotating until every database has been the held-out test set exactly once. This is useful for estimating how well a model generalizes to an unseen recording domain, rather than to a single other database.

databases needs at least 2 entries, and lodo is not compatible with reuse_train, train_extra, or use_splits.

Instead of heatmap.png, LODO mode writes:

  • results_lodo.txt: the overall LODO mean +/- std across fold means, plus each fold's own mean +/- std (and, if lodo_runs > 1, its individual per-run results).
  • lodo.png: a bar chart of each fold's mean result with error bars.

Two optional settings refine the fold loop:

  • lodo_dev: name of a database to exclude from the rotation and use as a fixed, genuine dev split (split_strategy = dev) in every fold, for real early-stopping instead of scoring epochs against the fold's own test set. Forces traindevtest = True. Must not also appear in databases.
  • lodo_runs: repeats each fold that many times (forcing EXP.runs = 1 per repeat) and reports each fold's mean +/- std across those repeats. Prefer this over EXP.runs for honest multi-seed averaging in LODO mode: with EXP.runs > 1, nkululeko returns only the single best-of-N-runs result per fold, not their mean. If MODEL.random_seed is set, every repeat would otherwise be identical, so lodo_runs is silently forced back down to 1 (with a warning).
[EXP]
root = ./experiments/lodo_demo/
databases = ['emodb', 'polish', 'emovo']
lodo = True
lodo_dev = for2sec
lodo_runs = 5
[DATA]
target = emotion
labels = ['neutral', 'happy', 'sad', 'angry']
[FEATS]
type = ['os']
[MODEL]
type = xgb
python -m nkululeko.multidb --config my_lodo_conf.ini

Nkululeko: oversample the training set

Sometimes, with categorically labeled data, the number of samples per class is very unevenly distributed, misleading the model to think that the overwhelming majority class is more important than the others.
In this case, two techniques might help: class weighting assigns a higher weight to samples from minority classes, and oversampling "invents" new samples for the minority classes.
With nkululeko since version 0.70.0, you can oversample the trainig set with different algorithms implemented by the imb_learn package.
You simply state the method in the FEATS section like so:

[FEATS]
...
balancing = adasyn # either ros, smote or adasyn

These methods are available:

  • ros: simply repeat random samples from the minority classes
  • smote: "invent" new minority samples by little changes from the existing ones
  • adasyn: similar to smote, but resulting in uneven class distributions
  • borderlinesmote: SMOTE variant focusing on borderline instances
  • svmsmote: SMOTE variant using SVM for generating synthetic samples

Under-sampling methods (reduce majority classes):

  • clustercentroids: replace majority class clusters with their centroids using K-means clustering
  • randomundersampler: randomly remove samples from majority classes
  • editednearestneighbours: remove noisy samples using edited nearest neighbors
  • tomeklinks: remove Tomek links to clean class boundaries

Combination methods (over-sampling + under-sampling):

  • smoteenn: combination of oversampling with SMOTE and undersampling with edited nearest neighbour (ENN)
  • smotetomek: combination of SMOTE oversampling and Tomek links undersampling

Nkululeko: re-name data column names

With nkululeko since version 0.68.1, you can re-name data fields (columns in your data table) by setting the following in your ini-file:

[DATA]
databases = ['mydata']
mydata.colnames = {'Participant ID':'speaker', 'sex':'gender', 'Age': 'age'}

which means, that, before further processing, the Participant ID field in your database mydata will be treated as speaker label and so on.

Nkululeko: automatically stratify your split sets

With nkululeko since version 0.68.0, the selection of test/dev vs. train samples can be done automatically in a stratified manner, i.e. trying to find splits that are age or gender balanced.
An example for such a configuration is this:

[DATA]
# the name of the database
databases = ['emodb']
# the location of the data
emodb = ./data/emodb/emodb
# set the split strategy to "balanced"
emodb.split_strategy = balanced
# set a percentage value for your test split
emodb.test_size = 20
# stratify variables with weights for importance
balance = {'emotion':2, 'age':1, 'gender':1}
# all stratification variables need to be categorical, 
# so we need to state the number of bins for "age" 
age_bins = 2
# a value for how much importance to give for the ideal group sizes
size_diff_weight = 1
# the target value of the experiment
target = emotion

Nkululeko will always keep the speaker variable disjunct, i.e. resulting splits will contain different speakers.
With the example above, the algorithm will try to balance emotion, gender and (binned) age distributions across the splits.

Nkululeko: inspect your data with Spotlight

With nkululeko since version 0.67.0, the spotlight software is directly integrated as part of the EXPLORE module.

You can simply run your data filters, augmentations, machine learning experiments, segmentations and model predictions as usual, and then call the spotlight software by adding to your configuration file:

[EXPL]
sample_selection = all # or train or test 
spotlight = True 

and running the EXPORE module

python -m nkululeko.explore --config myconfig.ini

Note that you might require to install an extra package:

pip install renumics-spotlight

A new web browser window should open as an interface to spotlight:

Torchaudio

If you use modules, feature-extractors or models that use torchaudio with Nkululeko, like e.g . Resampler or Squim model, you need to install the nightly version.

pip uninstall -y torch torchvision torchaudio
pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu