|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""AudioAE: a log-mel reconstruction autoencoder for audio anomaly detection. |
| 3 | +
|
| 4 | +Each clip is turned into overlapping log-mel context windows; a dense |
| 5 | +autoencoder is fit on the windows of the (mostly normal) training clips, |
| 6 | +and each clip is scored by its mean per-window reconstruction error. This |
| 7 | +is the DCASE-style audio anomaly detection baseline, expressed through |
| 8 | +PyOD's ``AutoEncoder`` so the training loop and preprocessing are shared |
| 9 | +with the rest of the library. |
| 10 | +""" |
| 11 | +# Author: Yue Zhao <yzhao062@gmail.com> |
| 12 | +# License: BSD 2 clause |
| 13 | + |
| 14 | +import numpy as np |
| 15 | +from sklearn.utils.validation import check_is_fitted |
| 16 | + |
| 17 | +from .base import BaseDetector |
| 18 | +from ..utils.encoders.audio import _to_mono_waveform |
| 19 | + |
| 20 | +_DEFAULT_SR = 22050 |
| 21 | + |
| 22 | + |
| 23 | +def _logmel_windows(y, sr, n_mels, context, hop_length): |
| 24 | + """Return overlapping log-mel context windows for one waveform. |
| 25 | +
|
| 26 | + Output shape is ``(n_windows, n_mels * context)``. Clips shorter than |
| 27 | + one context window are padded so at least one window is produced. |
| 28 | + """ |
| 29 | + import librosa |
| 30 | + |
| 31 | + spec = librosa.power_to_db( |
| 32 | + librosa.feature.melspectrogram( |
| 33 | + y=y, sr=sr, n_mels=n_mels, hop_length=hop_length)) |
| 34 | + n_frames = spec.shape[1] |
| 35 | + if n_frames < context: |
| 36 | + pad = np.zeros((n_mels, context - n_frames), dtype=spec.dtype) |
| 37 | + spec = np.concatenate([spec, pad], axis=1) |
| 38 | + n_frames = context |
| 39 | + windows = [spec[:, t:t + context].T.reshape(-1) |
| 40 | + for t in range(n_frames - context + 1)] |
| 41 | + return np.stack(windows).astype(np.float32) |
| 42 | + |
| 43 | + |
| 44 | +class AudioAE(BaseDetector): |
| 45 | + """Log-mel reconstruction autoencoder for audio anomaly detection. |
| 46 | +
|
| 47 | + The detector extracts overlapping log-mel context windows from each |
| 48 | + clip, fits a dense autoencoder (PyOD's :class:`AutoEncoder`) on the |
| 49 | + windows of the training clips, and scores each clip by its mean |
| 50 | + per-window reconstruction error. Training assumes the input is mostly |
| 51 | + normal, the usual unsupervised setting. |
| 52 | +
|
| 53 | + Requires ``torch`` (for the autoencoder) and ``pyod[audio]`` |
| 54 | + (``librosa``, ``soundfile``). |
| 55 | +
|
| 56 | + Parameters |
| 57 | + ---------- |
| 58 | + n_mels : int, optional (default=64) |
| 59 | + Number of mel bands in the spectrogram. |
| 60 | +
|
| 61 | + context : int, optional (default=5) |
| 62 | + Number of consecutive frames stacked into one autoencoder input |
| 63 | + window. The window dimensionality is ``n_mels * context``. |
| 64 | +
|
| 65 | + hop_length : int, optional (default=512) |
| 66 | + STFT hop length in samples. |
| 67 | +
|
| 68 | + sr : int, optional (default=22050) |
| 69 | + Target sample rate. File inputs are loaded at this rate; |
| 70 | + ``(waveform, sample_rate)`` tuples are resampled to it. |
| 71 | +
|
| 72 | + contamination : float, optional (default=0.1) |
| 73 | + Expected proportion of outliers, used for the clip-level |
| 74 | + threshold and labels. |
| 75 | +
|
| 76 | + epoch_num : int, optional (default=40) |
| 77 | + Autoencoder training epochs. |
| 78 | +
|
| 79 | + batch_size : int, optional (default=1024) |
| 80 | + Autoencoder mini-batch size (over frames, not clips). |
| 81 | +
|
| 82 | + lr : float, optional (default=1e-3) |
| 83 | + Learning rate. |
| 84 | +
|
| 85 | + hidden_neuron_list : list of int or None, optional (default=None) |
| 86 | + Encoder hidden sizes. ``None`` uses ``[128, 32, 8]``, which gives |
| 87 | + the DCASE-style 320-128-32-8 contraction for the default |
| 88 | + 320-dimensional window (``n_mels=64``, ``context=5``). |
| 89 | +
|
| 90 | + device : str or None, optional (default=None) |
| 91 | + Torch device. ``None`` auto-selects. |
| 92 | +
|
| 93 | + random_state : int, optional (default=42) |
| 94 | + Seed forwarded to the autoencoder. |
| 95 | +
|
| 96 | + verbose : int, optional (default=0) |
| 97 | + Autoencoder verbosity. |
| 98 | +
|
| 99 | + Attributes |
| 100 | + ---------- |
| 101 | + decision_scores_ : numpy array of shape (n_clips,) |
| 102 | + Clip-level outlier scores of the training data. |
| 103 | +
|
| 104 | + threshold_ : float |
| 105 | + Score threshold based on ``contamination``. |
| 106 | +
|
| 107 | + labels_ : numpy array of shape (n_clips,) |
| 108 | + Binary labels of training clips (0: inlier, 1: outlier). |
| 109 | +
|
| 110 | + ae_ : AutoEncoder |
| 111 | + The fitted frame-level autoencoder. |
| 112 | +
|
| 113 | + Examples |
| 114 | + -------- |
| 115 | + >>> import numpy as np |
| 116 | + >>> from pyod.models.audio_ae import AudioAE |
| 117 | + >>> clips = [np.random.RandomState(s).randn(22050) for s in range(20)] |
| 118 | + >>> clf = AudioAE(epoch_num=5) |
| 119 | + >>> clf.fit(clips) # doctest: +SKIP |
| 120 | + >>> scores = clf.decision_function(clips) # doctest: +SKIP |
| 121 | + """ |
| 122 | + |
| 123 | + def __init__(self, n_mels=64, context=5, hop_length=512, sr=_DEFAULT_SR, |
| 124 | + contamination=0.1, epoch_num=40, batch_size=1024, lr=1e-3, |
| 125 | + hidden_neuron_list=None, device=None, random_state=42, |
| 126 | + verbose=0): |
| 127 | + super(AudioAE, self).__init__(contamination=contamination) |
| 128 | + self.n_mels = n_mels |
| 129 | + self.context = context |
| 130 | + self.hop_length = hop_length |
| 131 | + self.sr = sr |
| 132 | + self.epoch_num = epoch_num |
| 133 | + self.batch_size = batch_size |
| 134 | + self.lr = lr |
| 135 | + self.hidden_neuron_list = hidden_neuron_list |
| 136 | + self.device = device |
| 137 | + self.random_state = random_state |
| 138 | + self.verbose = verbose |
| 139 | + |
| 140 | + def _extract(self, X): |
| 141 | + """Return (frames, clip_idx) over all clips in X.""" |
| 142 | + try: |
| 143 | + import librosa # noqa: F401 |
| 144 | + import soundfile # noqa: F401 |
| 145 | + except ImportError: |
| 146 | + raise ImportError( |
| 147 | + "AudioAE requires 'librosa' and 'soundfile'. " |
| 148 | + "Install with: pip install pyod[audio]") |
| 149 | + if len(X) == 0: |
| 150 | + raise ValueError("AudioAE received an empty input.") |
| 151 | + frames_list, clip_idx = [], [] |
| 152 | + for i, item in enumerate(X): |
| 153 | + y = _to_mono_waveform(item, self.sr) |
| 154 | + windows = _logmel_windows(y, self.sr, self.n_mels, |
| 155 | + self.context, self.hop_length) |
| 156 | + frames_list.append(windows) |
| 157 | + clip_idx.append(np.full(len(windows), i, dtype=np.int64)) |
| 158 | + return np.concatenate(frames_list, axis=0), np.concatenate(clip_idx) |
| 159 | + |
| 160 | + @staticmethod |
| 161 | + def _aggregate(frame_scores, clip_idx, n_clips): |
| 162 | + """Mean per-frame score within each clip.""" |
| 163 | + out = np.zeros(n_clips, dtype=np.float64) |
| 164 | + for i in range(n_clips): |
| 165 | + mask = clip_idx == i |
| 166 | + if mask.any(): |
| 167 | + out[i] = float(frame_scores[mask].mean()) |
| 168 | + return out |
| 169 | + |
| 170 | + def fit(self, X, y=None): |
| 171 | + """Fit the frame autoencoder and score the training clips. |
| 172 | +
|
| 173 | + Parameters |
| 174 | + ---------- |
| 175 | + X : list |
| 176 | + Audio clips as file paths, waveform arrays, or |
| 177 | + ``(waveform, sample_rate)`` tuples. |
| 178 | +
|
| 179 | + y : Ignored |
| 180 | + Not used, present for API consistency. |
| 181 | +
|
| 182 | + Returns |
| 183 | + ------- |
| 184 | + self : object |
| 185 | + """ |
| 186 | + try: |
| 187 | + import torch # noqa: F401 |
| 188 | + except ImportError: |
| 189 | + raise ImportError( |
| 190 | + "AudioAE requires torch (for the autoencoder) and " |
| 191 | + "pyod[audio] (librosa, soundfile). Install with: " |
| 192 | + "pip install pyod[torch,audio]") |
| 193 | + from .auto_encoder import AutoEncoder |
| 194 | + |
| 195 | + frames, clip_idx = self._extract(X) |
| 196 | + dim = frames.shape[1] |
| 197 | + hidden = self.hidden_neuron_list or [128, 32, 8] |
| 198 | + # Drop hidden layers that are not smaller than the input so the |
| 199 | + # autoencoder stays a contraction for unusually small windows. |
| 200 | + hidden = [h for h in hidden if h < dim] or [max(dim // 2, 2)] |
| 201 | + |
| 202 | + # Cap the batch size to the frame count. PyOD's AutoEncoder drops |
| 203 | + # the last incomplete batch, so a batch larger than the dataset |
| 204 | + # would drop every frame and leave the training loop with nothing. |
| 205 | + batch_size = max(1, min(self.batch_size, frames.shape[0])) |
| 206 | + |
| 207 | + self.ae_ = AutoEncoder( |
| 208 | + contamination=self.contamination, epoch_num=self.epoch_num, |
| 209 | + batch_size=batch_size, lr=self.lr, |
| 210 | + hidden_neuron_list=hidden, device=self.device, |
| 211 | + random_state=self.random_state, verbose=self.verbose) |
| 212 | + self.ae_.fit(frames) |
| 213 | + |
| 214 | + frame_scores = self.ae_.decision_function(frames) |
| 215 | + self._set_n_classes(y) |
| 216 | + self.decision_scores_ = self._aggregate(frame_scores, clip_idx, len(X)) |
| 217 | + self._process_decision_scores() |
| 218 | + return self |
| 219 | + |
| 220 | + def decision_function(self, X): |
| 221 | + """Predict clip-level anomaly scores for X. |
| 222 | +
|
| 223 | + Parameters |
| 224 | + ---------- |
| 225 | + X : list |
| 226 | + Audio clips in the same formats accepted by ``fit``. |
| 227 | +
|
| 228 | + Returns |
| 229 | + ------- |
| 230 | + anomaly_scores : numpy array of shape (n_clips,) |
| 231 | + """ |
| 232 | + check_is_fitted(self, ['decision_scores_', 'threshold_', 'labels_']) |
| 233 | + frames, clip_idx = self._extract(X) |
| 234 | + frame_scores = self.ae_.decision_function(frames) |
| 235 | + return self._aggregate(frame_scores, clip_idx, len(X)) |
0 commit comments