AI Logic

Data Augmentation

Speed perturbation

Updated:

Speed perturbation diagram. The left shows the training flow (training audio, change speed with 3 factors, triple the training data, regenerate alignments, extract features, acoustic model, loss). The right shows waveforms (whose length changes) and frequency components (whose positions shift by a factor of α) side by side for speed factors α of 0.9, 1.0, and 1.1, along with the equation y(t) = x(αt)

What is speed perturbation

Speed perturbation is a data augmentation method that makes copies of the training audio at slightly different speeds and trains speech recognition on them with the transcripts unchanged. It was proposed by Ko et al. in 2015. The setting the paper recommends is to make two copies of the original audio at 0.9× and 1.1× speed and combine them with the original for three times as much training data.

Changing the speed does not mean changing only the speaking rate. Like spinning a record or tape faster, it compresses or stretches the entire audio. Speeding it up therefore makes the audio shorter and the voice higher, and slowing it down makes the audio longer and the voice lower.

In equations, audio x(t)x(t) changed by a factor α\alpha becomes:

y(t)=x(αt)y(t) = x(\alpha t)

With α>1\alpha > 1 it becomes faster (shorter), and with α<1\alpha < 1 slower (longer). The target transcript is left unchanged.

As an analogy, it is like practicing by listening to the same person's voice remade into that of someone who speaks a little faster with a higher voice, or a little slower with a lower voice. The model learns to recognize the same words even when speaking rate and pitch differ from person to person.

Speed perturbation amounts to applying two augmentations in a single operation: one that changes voice pitch (vocal tract length) and one that changes speaking rate (tempo). In the paper, it achieved a lower word error rate than using either one alone.

How it works

Effect on frequency

Taking the Fourier transform of y(t)=x(αt)y(t) = x(\alpha t) gives the following (XX and YY are the Fourier transforms of xx and yy).

Y(ω)=1α X ⁣(ωα)Y(\omega) = \frac{1}{\alpha}\, X\!\left(\frac{\omega}{\alpha}\right)

A component at frequency ω0\omega_0 in the original audio moves to αω0\alpha \omega_0. In other words, frequency components shift in proportion to their frequency (right side of the figure at the top). Because the mel scale commonly used in speech recognition is roughly logarithmic, a proportional shift becomes approximately a translation along the frequency axis of the mel spectrogram. This is a change similar to that of the augmentation that mimics differences in speakers' vocal tract lengths (VTLP).

Unlike VTLP, however, speed perturbation also changes the length of the audio. At 0.9×, the length becomes about 1.1× (1/0.91/0.9×); at 1.1×, about 0.91×. The number of feature frames changes accordingly.

Procedure

The paper's procedure is as follows (left side of the figure at the top).

  1. Change the speed of every utterance in the training data to 0.9× and 1.1×. The paper used the speed function (resampling) of the audio tool SoX.
  2. Combine them with the original audio for three times as much training data. The transcripts stay the same.
  3. Because the audio length changes, in HMM-based speech recognition, regenerate the alignments for the copies (which frame corresponds to which phoneme) with a GMM-HMM.
  4. Train the acoustic model as usual on the tripled data.

Changing the speed by resampling works as follows. If audio at sampling rate fsf_s is treated as if it had been recorded at αfs\alpha f_s and resampled to fsf_s, the number of samples becomes 1/α1/\alpha times, and when played back at fsf_s it runs at α\alpha times the speed.

Changing the speed changes both the length and the pitch of the audio. It is a different operation from "tempo change" (such as SoX's tempo), which changes only the speaking rate and preserves pitch. In the paper's comparison, changing only the tempo was less effective than speed perturbation.

Why it works

The paper explains why speed perturbation works as follows.

  • It teaches differences in pitch and speaking rate at the same time: The frequency shift resembles differences in vocal tract length (VTLP), and the length change resembles differences in speaking rate (tempo). Speed perturbation mimics both at once, making the model robust to differences between speakers.
  • It improves generalization: With speed perturbation, the gap in per-frame likelihood between the training and validation data became smaller. This shows that the model was less able to memorize the training data.

The paper also notes that slowing down (α<1\alpha < 1) creates a band in which high-frequency energy is nearly zero. This happens because energy shifts toward lower frequencies, but the paper reports that it was not a problem in practice.

Results reported in the paper

This is a comparison of word error rates (%) on Switchboard (English telephone conversations, 300 hours). Evaluation is on Hub5 '00, where SWB is the Switchboard portion and CHE the CallHome portion (harder conversations). The acoustic model is a TDNN, and the input is 40-dimensional MFCCs.

MethodData multiplierEpochsSWBCHETotal
Baseline (no augmentation)1613.727.720.7
VTLP3213.126.519.9
VTLP5213.226.720.0
VTLP + time warping3213.326.820.1
Tempo change3213.527.020.3
Speed perturbation3213.126.119.7
Speed perturbation3612.925.719.3

The methods that triple the data reduce the number of epochs to 2 to keep training time equal. Because the model trained with speed perturbation still had low likelihood on the training data, increasing the epochs to 6 improved it further. Increasing the baseline's epochs, on the other hand, made it worse (in the GALE Mandarin experiment).

Word error rates also dropped on other tasks, regardless of the amount of training data.

TaskHours of training dataBaselineSpeed perturbationRelative improvement (%)
GALE (Mandarin broadcast news)100 hours17.5117.162.0
TED-LIUM (talks)118 hours17.917.23.9
Switchboard (telephone conversations)300 hours20.719.36.7
LibriSpeech (read speech)960 hours12.9312.513.2
ASpIRE (far-field microphones)5,500 hours30.830.70.32

Only on ASpIRE was the improvement small. The paper reasons that this task's baseline already augmented the training data with reverberated copies, which provided enough variation.

Caveats

  • The data triples, so training time increases too. The paper got improvements even when it reduced the number of epochs to keep training time equal, but adding more epochs improved results further.
  • HMM-based speech recognition needs regenerated alignments. Because the length changes, the original audio's alignments cannot be used as is. Training that does not need alignments, such as CTC, avoids this effort.
  • The effect can be smaller on data already heavily augmented. On ASpIRE in the paper, adding it on top of reverberation augmentation gave only a slight improvement.
  • It is not used at evaluation or inference. Only the training data has its speed changed.

torchaudio's transforms.SpeedPerturbation(orig_freq, factors) picks one factor at random from factors each time it is called. To use the original, 0.9×, and 1.1× in equal proportion as in the paper, set factors=[0.9, 1.0, 1.1]. Forgetting 1.0 means the model never trains on audio at the original speed. The output length also changes, so apply it before batching into mini-batches and update the lengths (lengths) as well.

Comparison with similar data augmentation methods and how to choose

The table below lines up data augmentation methods commonly used in speech recognition from the same angles.

MethodWhat it changesWhere it is appliedLengthMain settings to tune
Speed perturbationSpeed (length and pitch change together)WaveformChangesSpeed factors (0.9, 1.0, 1.1)
VTLPPitch (stretches or compresses the frequency scale)During feature extractionUnchangedWarp factor
Tempo changeSpeaking rate only (pitch preserved)WaveformChangesSpeed factor
SpecAugmentTime warping; masking frequency and time bandsLog mel spectrogramUnchangedWarp size, mask widths and counts
MixSpeechAdds the features of two utterancesFeatures−Distribution of the mixing ratio

Rough guidelines for choosing:

  • Improving speech recognition accuracy with little effort: Use speed perturbation. The only setting is the factors, and the paper's 0.9, 1.0, and 1.1 can be used as is.
  • Applying a different change each time during training with almost no extra computation: Use SpecAugment. It only masks parts of the features, so no waveform processing is needed.
  • Combining them: Speed perturbation is applied to the waveform and SpecAugment to the features, so both can be used together.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torchaudio
from torch.utils.data import DataLoader

"""
Speech recognition on LibriSpeech (trained with speed perturbation)
Paper's setting: speeds of 0.9x, 1.0x, and 1.1x. Here, one is chosen at random each time during training
(as in the paper, you can also prepare 3 copies in advance and triple the data)
"""

# Hyperparameters
sample_rate = 16000
factors = [0.9, 1.0, 1.1]   # speed factors (include 1.0 so the model also trains on audio at the original speed)
batch_size = 8
epochs = 1
learning_rate = 1e-3

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Speed perturbation: pick one factor at random from factors and change the speed by resampling (length changes too)
speed_perturb = torchaudio.transforms.SpeedPerturbation(orig_freq=sample_rate, factors=factors)
# To apply a single factor, use torchaudio.functional.speed(waveform, orig_freq, factor)
mfcc = torchaudio.transforms.MFCC(sample_rate=sample_rate, n_mfcc=40)   # the paper's input is 40-dim MFCC

dataset = torchaudio.datasets.LIBRISPEECH('./data', url='train-clean-100', download=True)
chars = list(" abcdefghijklmnopqrstuvwxyz'")
char_to_id = {c: i + 1 for i, c in enumerate(chars)}   # 0 is the CTC blank


def make_collate(train):
  def collate(batch):
    feats, feat_lens, targets, target_lens = [], [], [], []
    for waveform, sr, transcript, *_ in batch:
      if train:
        waveform, _ = speed_perturb(waveform)          # change speed only during training; transcript stays the same
      f = mfcc(waveform)[0].transpose(0, 1)            # [time, 40]
      feats.append(f)
      feat_lens.append(f.size(0))
      ids = [char_to_id[c] for c in transcript.lower() if c in char_to_id]
      targets.append(torch.tensor(ids))
      target_lens.append(len(ids))
    feats = nn.utils.rnn.pad_sequence(feats, batch_first=True)   # lengths change, so pad after applying it
    return feats, torch.tensor(feat_lens), torch.cat(targets), torch.tensor(target_lens)
  return collate


train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=make_collate(train=True))


class SmallASR(nn.Module):
  def __init__(self, n_in=40, hidden=256, n_out=len(chars) + 1):
    super().__init__()
    self.lstm = nn.LSTM(n_in, hidden, num_layers=2, batch_first=True, bidirectional=True)
    self.fc = nn.Linear(2 * hidden, n_out)

  def forward(self, x):
    return self.fc(self.lstm(x)[0])   # [B, time, number of characters + 1]


model = SmallASR().to(device)
ctc = nn.CTCLoss(blank=0, zero_infinity=True)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(epochs):
  model.train()
  for feats, feat_lens, targets, target_lens in train_loader:
    log_probs = model(feats.to(device)).log_softmax(dim=-1).transpose(0, 1)   # CTC expects [time, B, chars]
    loss = ctc(log_probs, targets, feat_lens, target_lens)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Evaluation/inference: do not change speed; feed the original audio as is
model.eval()
with torch.no_grad():
  waveform, sr, transcript, *_ = dataset[0]
  pred = model(mfcc(waveform)[0].transpose(0, 1)[None].to(device)).argmax(dim=-1)
  print(pred.shape, transcript)

FAQ

Q. Can factors other than 0.9, 1.0, and 1.1 be used?
A.

They can be changed, but the paper recommends and uses in its experiments the three factors 0.9, 1.0, and 1.1. Straying far from them can make pitch and length unnatural and move too far from the original speech. When changing them, check the word error rate on validation data.

Q. How does it differ from augmentation that changes the tempo?
A.

A tempo change alters only the speaking rate while preserving pitch (the shape of the spectrum). Speed perturbation changes the playback speed as a whole, so speed and pitch change together. In the paper's Switchboard experiment, the word error rate was 20.3% with tempo change and 19.7% with speed perturbation (both with tripled data and 2 epochs).

Q. Can it be used together with SpecAugment?
A.

Yes. Speed perturbation is applied to the waveform and SpecAugment to the features (log mel spectrogram), so they act at different stages. Change the waveform's speed first, extract features, and then apply SpecAugment.

References

  1. T. Ko, V. Peddinti, D. Povey, and S. Khudanpur, "Audio Augmentation for Speech Recognition," Interspeech, 2015.
  2. PyTorch, torchaudio.transforms.SpeedPerturbation