speechbrain.processing.features module

Low-level feature pipeline components

This library gathers functions that compute popular speech features over batches of data. All the classes are of type nn.Module. This gives the possibility to have end-to-end differentiability and to backpropagate the gradient through them. Our functions are a modified version the ones in torch audio toolkit (https://github.com/pytorch/audio).

Example

>>> import torch
>>> from speechbrain.dataio.dataio import read_audio
>>> signal =read_audio('tests/samples/single-mic/example1.wav')
>>> signal = signal.unsqueeze(0)
>>> compute_STFT = STFT(
...     sample_rate=16000, win_length=25, hop_length=10, n_fft=400
... )
>>> features = compute_STFT(signal)
>>> features = spectral_magnitude(features)
>>> compute_fbanks = Filterbank(n_mels=40)
>>> features = compute_fbanks(features)
>>> compute_mfccs = DCT(input_size=40, n_out=20)
>>> features = compute_mfccs(features)
>>> compute_deltas = Deltas(input_size=20)
>>> delta1 = compute_deltas(features)
>>> delta2 = compute_deltas(delta1)
>>> features = torch.cat([features, delta1, delta2], dim=2)
>>> compute_cw = ContextWindow(left_frames=5, right_frames=5)
>>> features  = compute_cw(features)
>>> norm = InputNormalization()
>>> features = norm(features, torch.tensor([1]).float())
Authors
  • Mirco Ravanelli 2020

Summary

Classes:

ContextWindow

Computes the context window.

DCT

Computes the discrete cosine transform.

Deltas

Computes delta coefficients (time derivatives).

DynamicRangeCompression

Dynamic range compression for audio signals - clipped log scale with an optional multiplier

Filterbank

computes filter bank (FBANK) features given spectral magnitudes.

GlobalNorm

A global normalization module - computes a single mean and standard deviation for the entire batch across unmasked positions and uses it to normalize the inputs to the desired mean and standard deviation.

ISTFT

Computes the Inverse Short-Term Fourier Transform (ISTFT)

InputNormalization

Performs mean and variance normalization of the input tensor.

MinLevelNorm

A commonly used normalization for the decibel scale

STFT

computes the Short-Term Fourier Transform (STFT).

Functions:

spectral_magnitude

Returns the magnitude of a complex spectrogram.

Reference

class speechbrain.processing.features.STFT(sample_rate, win_length=25, hop_length=10, n_fft=400, window_fn=<built-in method hamming_window of type object>, normalized_stft=False, center=True, pad_mode='constant', onesided=True)[source]

Bases: Module

computes the Short-Term Fourier Transform (STFT).

This class computes the Short-Term Fourier Transform of an audio signal. It supports multi-channel audio inputs (batch, time, channels).

Parameters:
  • sample_rate (int) – Sample rate of the input audio signal (e.g 16000).

  • win_length (float) – Length (in ms) of the sliding window used to compute the STFT.

  • hop_length (float) – Length (in ms) of the hope of the sliding window used to compute the STFT.

  • n_fft (int) – Number of fft point of the STFT. It defines the frequency resolution (n_fft should be <= than win_len).

  • window_fn (function) – A function that takes an integer (number of samples) and outputs a tensor to be multiplied with each window before fft.

  • normalized_stft (bool) – If True, the function returns the normalized STFT results, i.e., multiplied by win_length^-0.5 (default is False).

  • center (bool) – If True (default), the input will be padded on both sides so that the t-th frame is centered at time t×hop_length. Otherwise, the t-th frame begins at time t×hop_length.

  • pad_mode (str) – It can be ‘constant’,’reflect’,’replicate’, ‘circular’, ‘reflect’ (default). ‘constant’ pads the input tensor boundaries with a constant value. ‘reflect’ pads the input tensor using the reflection of the input boundary. ‘replicate’ pads the input tensor using replication of the input boundary. ‘circular’ pads using circular replication.

  • onesided (True) – If True (default) only returns nfft/2 values. Note that the other samples are redundant due to the Fourier transform conjugate symmetry.

Example

>>> import torch
>>> compute_STFT = STFT(
...     sample_rate=16000, win_length=25, hop_length=10, n_fft=400
... )
>>> inputs = torch.randn([10, 16000])
>>> features = compute_STFT(inputs)
>>> features.shape
torch.Size([10, 101, 201, 2])
forward(x)[source]

Returns the STFT generated from the input waveforms.

Parameters:

x (tensor) – A batch of audio signals to transform.

training: bool
class speechbrain.processing.features.ISTFT(sample_rate, n_fft=None, win_length=25, hop_length=10, window_fn=<built-in method hamming_window of type object>, normalized_stft=False, center=True, onesided=True, epsilon=1e-12)[source]

Bases: Module

Computes the Inverse Short-Term Fourier Transform (ISTFT)

This class computes the Inverse Short-Term Fourier Transform of an audio signal. It supports multi-channel audio inputs (batch, time_step, n_fft, 2, n_channels [optional]).

Parameters:
  • sample_rate (int) – Sample rate of the input audio signal (e.g. 16000).

  • win_length (float) – Length (in ms) of the sliding window used when computing the STFT.

  • hop_length (float) – Length (in ms) of the hope of the sliding window used when computing the STFT.

  • window_fn (function) – A function that takes an integer (number of samples) and outputs a tensor to be used as a window for ifft.

  • normalized_stft (bool) – If True, the function assumes that it’s working with the normalized STFT results. (default is False)

  • center (bool) – If True (default), the function assumes that the STFT result was padded on both sides.

  • onesided (True) – If True (default), the function assumes that there are n_fft/2 values for each time frame of the STFT.

  • epsilon (float) – A small value to avoid division by 0 when normalizing by the sum of the squared window. Playing with it can fix some abnormalities at the beginning and at the end of the reconstructed signal. The default value of epsilon is 1e-12.

Example

>>> import torch
>>> compute_STFT = STFT(
...     sample_rate=16000, win_length=25, hop_length=10, n_fft=400
... )
>>> compute_ISTFT = ISTFT(
...     sample_rate=16000, win_length=25, hop_length=10
... )
>>> inputs = torch.randn([10, 16000])
>>> outputs = compute_ISTFT(compute_STFT(inputs))
>>> outputs.shape
torch.Size([10, 16000])
forward(x, sig_length=None)[source]

Returns the ISTFT generated from the input signal.

Parameters:
  • x (tensor) – A batch of audio signals in the frequency domain to transform.

  • sig_length (int) – The length of the output signal in number of samples. If not specified will be equal to: (time_step - 1) * hop_length + n_fft

training: bool
speechbrain.processing.features.spectral_magnitude(stft, power: int = 1, log: bool = False, eps: float = 1e-14)[source]

Returns the magnitude of a complex spectrogram.

Parameters:
  • stft (torch.Tensor) – A tensor, output from the stft function.

  • power (int) – What power to use in computing the magnitude. Use power=1 for the power spectrogram. Use power=0.5 for the magnitude spectrogram.

  • log (bool) – Whether to apply log to the spectral features.

Example

>>> a = torch.Tensor([[3, 4]])
>>> spectral_magnitude(a, power=0.5)
tensor([5.])
class speechbrain.processing.features.Filterbank(n_mels=40, log_mel=True, filter_shape='triangular', f_min=0, f_max=8000, n_fft=400, sample_rate=16000, power_spectrogram=2, amin=1e-10, ref_value=1.0, top_db=80.0, param_change_factor=1.0, param_rand_factor=0.0, freeze=True)[source]

Bases: Module

computes filter bank (FBANK) features given spectral magnitudes.

Parameters:
  • n_mels (float) – Number of Mel filters used to average the spectrogram.

  • log_mel (bool) – If True, it computes the log of the FBANKs.

  • filter_shape (str) – Shape of the filters (‘triangular’, ‘rectangular’, ‘gaussian’).

  • f_min (int) – Lowest frequency for the Mel filters.

  • f_max (int) – Highest frequency for the Mel filters.

  • n_fft (int) – Number of fft points of the STFT. It defines the frequency resolution (n_fft should be<= than win_len).

  • sample_rate (int) – Sample rate of the input audio signal (e.g, 16000)

  • power_spectrogram (float) – Exponent used for spectrogram computation.

  • amin (float) – Minimum amplitude (used for numerical stability).

  • ref_value (float) – Reference value used for the dB scale.

  • top_db (float) – Minimum negative cut-off in decibels.

  • freeze (bool) – If False, it the central frequency and the band of each filter are added into nn.parameters. If True, the standard frozen features are computed.

  • param_change_factor (bool) – If freeze=False, this parameter affects the speed at which the filter parameters (i.e., central_freqs and bands) can be changed. When high (e.g., param_change_factor=1) the filters change a lot during training. When low (e.g. param_change_factor=0.1) the filter parameters are more stable during training

  • param_rand_factor (float) – This parameter can be used to randomly change the filter parameters (i.e, central frequencies and bands) during training. It is thus a sort of regularization. param_rand_factor=0 does not affect, while param_rand_factor=0.15 allows random variations within +-15% of the standard values of the filter parameters (e.g., if the central freq is 100 Hz, we can randomly change it from 85 Hz to 115 Hz).

Example

>>> import torch
>>> compute_fbanks = Filterbank()
>>> inputs = torch.randn([10, 101, 201])
>>> features = compute_fbanks(inputs)
>>> features.shape
torch.Size([10, 101, 40])
forward(spectrogram)[source]

Returns the FBANks.

Parameters:

x (tensor) – A batch of spectrogram tensors.

training: bool
class speechbrain.processing.features.DCT(input_size, n_out=20, ortho_norm=True)[source]

Bases: Module

Computes the discrete cosine transform.

This class is primarily used to compute MFCC features of an audio signal given a set of FBANK features as input.

Parameters:
  • input_size (int) – Expected size of the last dimension in the input.

  • n_out (int) – Number of output coefficients.

  • ortho_norm (bool) – Whether to use orthogonal norm.

Example

>>> import torch
>>> inputs = torch.randn([10, 101, 40])
>>> compute_mfccs = DCT(input_size=inputs.size(-1))
>>> features = compute_mfccs(inputs)
>>> features.shape
torch.Size([10, 101, 20])
forward(x)[source]

Returns the DCT of the input tensor.

Parameters:

x (tensor) – A batch of tensors to transform, usually fbank features.

training: bool
class speechbrain.processing.features.Deltas(input_size, window_length=5)[source]

Bases: Module

Computes delta coefficients (time derivatives).

Parameters:

win_length (int) – Length of the window used to compute the time derivatives.

Example

>>> inputs = torch.randn([10, 101, 20])
>>> compute_deltas = Deltas(input_size=inputs.size(-1))
>>> features = compute_deltas(inputs)
>>> features.shape
torch.Size([10, 101, 20])
forward(x)[source]

Returns the delta coefficients.

Parameters:

x (tensor) – A batch of tensors.

training: bool
class speechbrain.processing.features.ContextWindow(left_frames=0, right_frames=0)[source]

Bases: Module

Computes the context window.

This class applies a context window by gathering multiple time steps in a single feature vector. The operation is performed with a convolutional layer based on a fixed kernel designed for that.

Parameters:
  • left_frames (int) – Number of left frames (i.e, past frames) to collect.

  • right_frames (int) – Number of right frames (i.e, future frames) to collect.

Example

>>> import torch
>>> compute_cw = ContextWindow(left_frames=5, right_frames=5)
>>> inputs = torch.randn([10, 101, 20])
>>> features = compute_cw(inputs)
>>> features.shape
torch.Size([10, 101, 220])
forward(x)[source]

Returns the tensor with the surrounding context.

Parameters:

x (tensor) – A batch of tensors.

training: bool
class speechbrain.processing.features.InputNormalization(mean_norm=True, std_norm=True, norm_type='global', avg_factor=None, requires_grad=False, update_until_epoch=3)[source]

Bases: Module

Performs mean and variance normalization of the input tensor.

Parameters:
  • mean_norm (True) – If True, the mean will be normalized.

  • std_norm (True) – If True, the standard deviation will be normalized.

  • norm_type (str) – It defines how the statistics are computed (‘sentence’ computes them at sentence level, ‘batch’ at batch level, ‘speaker’ at speaker level, while global computes a single normalization vector for all the sentences in the dataset). Speaker and global statistics are computed with a moving average approach.

  • avg_factor (float) – It can be used to manually set the weighting factor between current statistics and accumulated ones.

Example

>>> import torch
>>> norm = InputNormalization()
>>> inputs = torch.randn([10, 101, 20])
>>> inp_len = torch.ones([10])
>>> features = norm(inputs, inp_len)
Dict

alias of Dict

spk_dict_mean: Dict[int, Tensor]
spk_dict_std: Dict[int, Tensor]
spk_dict_count: Dict[int, int]
forward(x, lengths, spk_ids=tensor([]), epoch=0)[source]

Returns the tensor with the surrounding context.

Parameters:
  • x (tensor) – A batch of tensors.

  • lengths (tensor) – A batch of tensors containing the relative length of each sentence (e.g, [0.7, 0.9, 1.0]). It is used to avoid computing stats on zero-padded steps.

  • spk_ids (tensor containing the ids of each speaker (e.g, [0 10 6]).) – It is used to perform per-speaker normalization when norm_type=’speaker’.

to(device)[source]

Puts the needed tensors in the right device.

class speechbrain.processing.features.GlobalNorm(norm_mean=0.0, norm_std=1.0, update_steps=None, length_dim=2, mask_value=0.0)[source]

Bases: Module

A global normalization module - computes a single mean and standard deviation for the entire batch across unmasked positions and uses it to normalize the inputs to the desired mean and standard deviation.

This normalization is reversible - it is possible to use the .denormalize() method to reover the original values.

Parameters:
  • norm_mean (float) – the desired normalized mean

  • norm_std (float) – the desired normalized standard deviation

  • update_steps (float) – the number of steps over which statistics will be collected

  • length_dim (int) – the dimension used to represent the length

  • mask_value (float) – the value with which to fill masked positions without a mask_value, the masked positions would be normalized, which might not be desired

Example

>>> import torch
>>> from speechbrain.processing.features import GlobalNorm
>>> global_norm = GlobalNorm(
...     norm_mean=0.5,
...     norm_std=0.2,
...     update_steps=3,
...     length_dim=1
... )
>>> x = torch.tensor([[1., 2., 3.]])
>>> x_norm = global_norm(x)
>>> x_norm
tensor([[0.3000, 0.5000, 0.7000]])
>>> x = torch.tensor([[5., 10., -4.]])
>>> x_norm = global_norm(x)
>>> x_norm
tensor([[0.6071, 0.8541, 0.1623]])
>>> x_denorm = global_norm.denormalize(x_norm)
>>> x_denorm
tensor([[ 5.0000, 10.0000, -4.0000]])
>>> x = torch.tensor([[100., -100., -50.]])
>>> global_norm.freeze()
>>> global_norm(x)
tensor([[ 5.3016, -4.5816, -2.1108]])
>>> global_norm.denormalize(x_norm)
tensor([[ 5.0000, 10.0000, -4.0000]])
>>> global_norm.unfreeze()
>>> global_norm(x)
tensor([[ 5.3016, -4.5816, -2.1108]])
>>> global_norm.denormalize(x_norm)
tensor([[ 5.0000, 10.0000, -4.0000]])
forward(x, lengths=None, mask_value=None, skip_update=False)[source]

Normalizes the tensor provided

Parameters:
  • x (torch.Tensor) – the tensor to normalize

  • lengths (torch.Tensor) – a tensor of relative lengths (padding will not count towards normalization)

  • mask_value (float) – the value to use for masked positions

  • skip_update (false) – whether to skip updates to the norm

Returns:

result – the normalized tensor

Return type:

torch.Tensor

normalize(x)[source]

Performs the normalization operation against the running mean and standard deviation

Parameters:

x (torch.Tensor) – the tensor to normalize

Returns:

result – the normalized tensor

Return type:

torch.Tensor

get_mask(x, lengths)[source]

Returns the length mask for the specified tensor

Parameters:
Returns:

mask – the mask tensor

Return type:

torch.Tensor

denormalize(x)[source]

Reverses the normalization proces

Parameters:

x (torch.Tensor) – a normalized tensor

Returns:

result – a denormalized version of x

Return type:

torch.Tensor

freeze()[source]

Stops updates to the running mean/std

unfreeze()[source]

Resumes updates to the running mean/std

training: bool
class speechbrain.processing.features.MinLevelNorm(min_level_db)[source]

Bases: Module

A commonly used normalization for the decibel scale

The scheme is as follows

x_norm = (x - min_level_db)/-min_level_db * 2 - 1

The rationale behind the scheme is as follows:

The top of the scale is assumed to be 0db. x_rel = (x - min) / (max - min) gives the relative position on the scale between the minimum and the maximum where the minimum is 0. and the maximum is 1.

The subsequent rescaling (x_rel * 2 - 1) puts it on a scale from -1. to 1. with the middle of the range centered at zero.

Parameters:

min_level_db (float) – the minimum level

Example

>>> norm = MinLevelNorm(min_level_db=-100.)
>>> x = torch.tensor([-50., -20., -80.])
>>> x_norm = norm(x)
>>> x_norm
tensor([ 0.0000,  0.6000, -0.6000])
training: bool
forward(x)[source]

Normalizes audio features in decibels (usually spectrograms)

Parameters:

x (torch.Tensor) – input features

Returns:

normalized_features – the normalized features

Return type:

torch.Tensor

denormalize(x)[source]

Reverses the min level normalization process

Parameters:

x (torch.Tensor) – the normalized tensor

Returns:

result – the denormalized tensor

Return type:

torch.Tensor

class speechbrain.processing.features.DynamicRangeCompression(multiplier=1, clip_val=1e-05)[source]

Bases: Module

Dynamic range compression for audio signals - clipped log scale with an optional multiplier

Parameters:
  • multiplier (float) – the multiplier constant

  • clip_val (float) – the minimum accepted value (values below this minimum will be clipped)

Example

>>> drc = DynamicRangeCompression()
>>> x = torch.tensor([10., 20., 0., 30.])
>>> drc(x)
tensor([  2.3026,   2.9957, -11.5129,   3.4012])
>>> drc = DynamicRangeCompression(2.)
>>> x = torch.tensor([10., 20., 0., 30.])
>>> drc(x)
tensor([  2.9957,   3.6889, -10.8198,   4.0943])
training: bool
forward(x)[source]

Performs the forward pass

Parameters:

x (torch.Tensor) – the source signal

Returns:

result – the result

Return type:

torch.Tensor