Winning Kaggle the Reproducible Way

Interactive chapter

This page shows the chapter notebook with its saved results. Constructed examples do not measure competition gains.

Chapter 64: Audio and Signal Competitions

Try the decision first

How far does chunk-level cross-validation overstate accuracy on new recordings, and does it distort the comparison between models?

Write your expectation before opening the worked results. Use the chapter activity to compare supported inputs. To change the calculation itself, run the notebook on GitHub.

Your answers stay on this page until you download them. They are not sent to a server.

Open the chapter activity

Worked notebook and saved results

How far does chunk-level cross-validation overstate accuracy on new recordings, and does it distort the comparison between models?

The chapter says to keep overlapping chunks from the same independent source together when the assessment requires unseen sources. The error is large, grows with the number of chunks per recording, and can manufacture a model lead that new recordings do not show.

Constructed data; the size of the optimism depends on how distinctive each recording's background is and how many chunks it yields. The flexible-model lead on new recordings is small in this generator, so the activity claims no real advantage for either model.

The experiment

Constructed audio: 60 recordings of two species, each with its own background (a random smooth frequency response standing in for site and microphone) and each cut into chunks of 512 samples. Half of a recording's chunks contain its species' call tone. Features are 24 log band powers from an FFT. A flexible model (extremely randomized trees, standing in for a CNN) and a simple one (logistic regression) are scored by pooled AUC under 5-fold cross-validation that splits by chunk, 5-fold cross-validation that splits by recording, and on 100 recordings the models never saw. The control is the number of chunks per recording.

Calculation code
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GroupKFold, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from kaggle_companion.activities._common import clean

SEED = 64
REPLICATES = 5                  # independent constructed collections; every estimate is their mean
RECORDINGS, NEW_RECORDINGS, NEW_CHUNKS = 60, 100, 4
CHUNK, BANDS = 512, 24          # samples per chunk; log-spectrum bands used as features
CALL_AMP = 0.5                  # loudness of the call tone relative to unit-variance background noise
CALL_FREQ = {0: 0.16, 1: 0.24}  # call frequency of species 0 and 1, in cycles per sample
MODELS = ["flexible", "simple"]


def recording_background(rng):
    """Each recording has its own background: a smooth random frequency response (a stand-in for site and microphone)."""
    return rng.normal(0, 3.0, 4) / np.arange(1, 5) ** 0.5, rng.uniform(0, 2 * np.pi, 4)


def chunk_features(background, species, rng, n):
    """n chunks of one recording as log band powers. Background noise is shaped by the recording's response; each chunk
    carries the species' call tone with probability 0.5."""
    amp, phase = background
    freq = np.fft.rfftfreq(CHUNK)
    gain_db = sum(a * np.cos(2 * np.pi * (i + 1) * freq * 2 + p) for i, (a, p) in enumerate(zip(amp, phase)))
    noise = np.fft.irfft(np.fft.rfft(rng.normal(size=(n, CHUNK)), axis=1) * 10 ** (gain_db / 20), CHUNK, axis=1)
    t, window = np.arange(CHUNK), np.hanning(CHUNK)
    call_freq = CALL_FREQ[species] * (1 + rng.normal(0, 0.04, n))
    tone = CALL_AMP * np.sin(2 * np.pi * call_freq[:, None] * t + rng.uniform(0, 2 * np.pi, (n, 1))) * np.sqrt(window)
    signal = noise + (rng.random(n) < 0.5)[:, None] * tone
    power = np.abs(np.fft.rfft(signal * window, axis=1)) ** 2
    width = (CHUNK // 2) // BANDS
    return np.log(power[:, :BANDS * width].reshape(n, BANDS, width).mean(2) + 1e-9)


def collection(recordings, chunks, rng):
    """Recordings alternate between the two species; every chunk inherits its recording's species and id."""
    X, y, group = [], [], []
    for r in range(recordings):
        X.append(chunk_features(recording_background(rng), r % 2, rng, chunks))
        y += [r % 2] * chunks
        group += [r] * chunks
    return np.vstack(X), np.array(y), np.array(group)


def make_model(kind):
    if kind == "flexible":      # a high-capacity learner standing in for a CNN: it can memorize recordings
        return ExtraTreesClassifier(40, max_features=0.5, random_state=0, n_jobs=1)
    return make_pipeline(StandardScaler(), LogisticRegression(C=10, max_iter=300))


def pooled_auc(model_kind, X, y, splits):
    """Pool every held-out prediction and score one AUC over them."""
    oof = np.zeros(len(y))
    for fit, hold in splits:
        oof[hold] = make_model(model_kind).fit(X[fit], y[fit]).predict_proba(X[hold])[:, 1]
    return roc_auc_score(y, oof)


def run(chunks_per_recording):
    scores = {m: {"chunk_cv": [], "recording_cv": [], "new_recordings": []} for m in MODELS}
    for rep in range(REPLICATES):
        rng = np.random.default_rng(SEED * 100 + rep)
        X, y, group = collection(RECORDINGS, chunks_per_recording, rng)
        X_new, y_new, _ = collection(NEW_RECORDINGS, NEW_CHUNKS, rng)        # recordings the model never saw
        for m in MODELS:
            scores[m]["chunk_cv"].append(pooled_auc(m, X, y, KFold(5, shuffle=True, random_state=rep).split(X)))
            scores[m]["recording_cv"].append(pooled_auc(m, X, y, GroupKFold(5).split(X, y, group)))
            scores[m]["new_recordings"].append(roc_auc_score(y_new, make_model(m).fit(X, y).predict_proba(X_new)[:, 1]))
    return clean({
        "chunks_per_recording": chunks_per_recording,
        **{m: {k: float(np.mean(v)) for k, v in scores[m].items()} for m in MODELS},
        "per_replicate": scores,
        "recordings": RECORDINGS, "training_chunks": RECORDINGS * chunks_per_recording, "new_chunks": NEW_RECORDINGS * NEW_CHUNKS,
        "replicates": REPLICATES,
    })

Measure it across the control

The control is chunks cut from each recording. Each value below runs the whole experiment from the generator up.

Calculation code
import pandas as pd
from kaggle_companion.activities.ch64 import explain

VALUES = [1, 3, 8, 16]
results = {value: run(value) for value in VALUES}
table = pd.DataFrame({str(v): explain(results[v], v)['metrics'] for v in VALUES})
print(table.to_string())
                                      1       3       8      16
Flexible, chunk-level CV          0.590   0.829   0.895   0.940
Flexible, recording-level CV      0.613   0.656   0.628   0.651
Flexible, new recordings          0.667   0.641   0.684   0.723
Simple, new recordings            0.647   0.622   0.675   0.705
Chunk-level optimism (flexible)  -0.077  +0.188  +0.211  +0.217

Look at it

The figure shows the default setting, chunks cut from each recording = 8.

Calculation code
import matplotlib.pyplot as plt
from kaggle_companion.activities.ch64 import draw, NCOLS, HEIGHT

DEFAULT = 8
fig, axes = plt.subplots(1, NCOLS, figsize=(6.6 if NCOLS == 1 else 10.4, HEIGHT), layout='constrained')
draw(axes, results[DEFAULT], DEFAULT)
plt.show()
Saved figure from this chapter calculation

What the result says

With 8 chunks per recording, the flexible model scores AUC 0.684 on new recordings. Chunk-level cross-validation reports 0.895, an optimism of 0.895 - 0.684 = 0.211; recording-level cross-validation reports 0.628. The flexible model's AUC minus the simple model's is +0.154 under chunk-level validation, -0.011 under recording-level validation and +0.009 on new recordings.

Apply this to your competition

Book location: Chapter 64, Record-Level Cross-Validation Is Not Optional.

Technical corrections

Apply a lesson from this chapter

Select a lesson whose conditions match your project. State how you would test it and what would make you reject it.

Ensure mixed audio actually overlaps

Conditions

  • variable-length waveforms are mixed for augmentation

Action

  • Align padded waveforms so nonzero audio content overlaps before mixing, and combine labels consistently.

Check

  • Inspect nonzero overlap and mixed labels on variable-length boundary cases; compare with the unchanged audio augmentation recipe.

Limits

  • Source small/deeper ensemble comparison is separate from this padding decision.
  • Mixing weights and labels must remain consistent; overlap alone does not establish benefit.

Find source links and value grades in the lesson atlas

Suppress pseudo-label noise between self-training iterations

Conditions

  • later noisy-student iterations stop converging

Action

  • Proposed conditional application: Apply a power greater than one to probabilities before the next iteration instead of temperature scaling logits, then stop if another iteration fails to improve.

Check

  • Proposed check: Tune powers on independent soundscapes at fixed architecture; inspect label calibration, rare recall and stopping criteria.

Limits

  • Shrinking probabilities can remove real weak positives; multiple retraining iterations are costly.

Find source links and value grades in the lesson atlas

Treat spectrogram template extraction as a cached expensive stage

Conditions

  • bird audio contains reusable local spectral motifs

Action

  • Proposed adaptation of source observation: Cache patch/template features and compare their contribution before repeating costly extraction.

Check

  • Proposed verification: Measure AUC with feature-family ablations and inspect reproducible cache provenance.

Limits

  • Pattern extraction details are not specified and repeated CV-based exports can bias selection.

Find source links and value grades in the lesson atlas

Cache pseudo-labels at sufficient temporal granularity

Conditions

  • self-training repeatedly samples long soundscapes

Action

  • Proposed adaptation of source observation: Cache teacher outputs at useful granularity and test confidence-based sampling rather than assuming finer labels are better.

Check

  • Proposed verification: Compare labeling accuracy, storage, sampling coverage and student score across granularities.

Limits

  • Confidence-to-correctness relation may shift by species; this packet does not give a final sampling algorithm.

Find source links and value grades in the lesson atlas

Reduce sound-event capacity when per-class recordings are scarce

Conditions

  • audio classification has about a hundred recordings per class

Action

  • Proposed adaptation of source observation: Compare a smaller pretrained feature extractor and attention block, tuning epochs separately for mixup.

Check

  • Proposed verification: Measure held-out overfitting, parameter count and quality per training budget.

Limits

  • Reduced overfitting was the author’s rationale, not an isolated demonstrated cause.

Find source links and value grades in the lesson atlas

Distinguish noisy-student regularization from naive pseudo-label concatenation

Conditions

  • pseudo-labeled soundscapes are noisier than clean labeled clips

Action

  • Proposed adaptation of source observation: Compare fixed balanced waveform mixing and stochastic depth during self-training against simple concatenation and supervised-only regularization.

Check

  • Proposed verification: Audit pseudo-label errors and evaluate every component separately under the same budget.

Limits

  • The explanation is the author’s interpretation; 0.5 weights and 0.15 drop-path are local settings.

Find source links and value grades in the lesson atlas

Require agreement between clip and frame event predictions

Conditions

  • sound-event false positives occur across short intervals

Action

  • Compare joint clip/frame probability gating with frame-only predictions.

Check

  • Measure false positives and missed events across neighboring thresholds on independent soundscapes.

Limits

  • Source thresholds were selected through leaderboard feedback and may not transfer.
  • SpecAugment TTA and positive-label loss monitoring are separate contextual practices.

Find source links and value grades in the lesson atlas

Retune optimization when comparing audio losses

Conditions

  • audio loss comparisons change gradient scale

Action

  • Proposed adaptation of source observation: Compare losses with separately tuned training budgets and explicitly document target normalization.

Check

  • Proposed verification: Evaluate rare and common classes using the same metric and splits.

Limits

  • The proposed causal explanation of CE is speculative and unnormalized labels change sample weights.

Find source links and value grades in the lesson atlas

Test inference activation and conservative ensemble reduction

Conditions

  • mostly single-label audio training uses CE but evaluation is multi-label

Action

  • Proposed conditional application: Compare sigmoid inference from CE-trained logits and minimum reduction across models with softmax and mean reduction.

Check

  • Proposed check: Ablate activation and mean/min reduction separately on held-out soundscapes; inspect missed calls and calibration.

Limits

  • Sigmoid of multiclass logits is not calibrated multilabel probability; minimum may erase valid detections.

Find source links and value grades in the lesson atlas

Choose audio backbones using speed as well as score

Conditions

  • audio classification has CPU inference constraints

Action

  • Proposed conditional application: Compare simple pretrained CNN backbones with more complex architectures; reject equal-score models that take much longer.

Check

  • Proposed check: Benchmark each backbone on identical audio, CPU and metric; retain accuracy-latency Pareto options.

Limits

  • Equal results are qualitative; architecture conclusion is setup-specific.

Find source links and value grades in the lesson atlas

Validate external audio before expanding training data

Conditions

  • external species recordings appear relevant but differ from target data

Action

  • Proposed conditional application: Compare the existing data with filtered external Xeno-Canto additions before adopting them.

Check

  • Proposed check: Compare additions on recording-disjoint target-domain holdouts, stratified by species and recording conditions.

Limits

  • External labeling and acquisition shifts can outweigh sample count.

Find source links and value grades in the lesson atlas

Compile fixed-shape audio inference and reuse spectral inputs

Conditions

  • many models consume the same mel spectrograms

Action

  • Proposed conditional application: Compile with OpenVINO, compute spectrograms in parallel and retain them in RAM for model reuse.

Check

  • Proposed check: Check compiled output parity; benchmark wall time and peak RAM with and without shared spectrogram caching.

Limits

  • RAM cache can exceed memory; compilation is hardware/shape dependent.

Find source links and value grades in the lesson atlas

Blend models from different self-training stages

Conditions

  • successive pseudo-label iterations may overfit

Action

  • Proposed conditional application: Ensemble supervised and different self-training-stage models rather than only the final-stage ensemble.

Check

  • Proposed check: Compare final-stage-only with stage-diverse blends at equal model count on untouched soundscapes.

Limits

  • More stages/backbones confound benefit; public tuning can still overfit.

Find source links and value grades in the lesson atlas

Compare pretrained speech representations with a compact CNN baseline

Conditions

  • speech-command recognition has limited domain labels

Action

  • Proposed conditional application: Fine-tune a pretrained HuBERT model and evaluate it alongside a small ResNet on the same command task.

Check

  • Proposed check: Compare small CNN and pretrained speech model on speaker-isolated command data, including latency, memory and noisy-channel accuracy.

Limits

  • The reported model comparison combines architecture, scale and pretraining; it is not an isolated pretraining ablation.

Find source links and value grades in the lesson atlas

Tune mel time and frequency resolution under inference limits

Conditions

  • long audio inputs require distinguishing narrow-band species calls

Action

  • Proposed adaptation of source observation: Sweep hop length and mel-band count jointly under the end-to-end inference budget.

Check

  • Proposed verification: Compare species-wise metric and runtime across time/frequency resolutions.

Limits

  • The narrow-call explanation is attributed and no isolated numeric comparison is given.

Find source links and value grades in the lesson atlas

Balance long soundscapes with short clips through segmentation

Conditions

  • one sampled chunk per file underweights long unlabeled soundscapes

Action

  • Proposed conditional application: Treat twenty-, thirty- or sixty-second audio segments as separate files and adjust epochs for the changed steps per epoch.

Check

  • Proposed check: Compare file-level and segment-level sampling at equal optimizer steps on recording-disjoint validation.

Limits

  • Segments from the same recording must remain in one split; epoch counts are not equal work.

Find source links and value grades in the lesson atlas

Estimate audio experiment variance with repeated folds

Conditions

  • noisy score feedback obscures architecture comparisons

Action

  • Proposed adaptation of source observation: Use several fold or seed models per setup and compare their mean and variability; proposed independent holdouts remain essential.

Check

  • Proposed verification: Track seed/fold dispersion and avoid excessive feedback-driven selection.

Limits

  • The author relied on public LB because CV disagreed; ensembling does not eliminate leaderboard overfitting.

Find source links and value grades in the lesson atlas

Downweight low-information pseudo-labeled soundscapes

Conditions

  • pseudo-label confidence varies among long audio samples

Action

  • Proposed conditional application: Weight soundscape sampling by the sum of maximum label probabilities, then train on random twenty-second intervals.

Check

  • Proposed check: Compare weighted and uniform sampling at equal steps; audit pseudo-label correctness and rare/no-call coverage.

Limits

  • Probability sum also measures call density and can suppress rare quiet recordings.

Find source links and value grades in the lesson atlas