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('samples/audio_samples/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).

Filterbank

computes filter bank (FBANK) features given spectral magnitudes.

ISTFT

Computes the Inverse Short-Term Fourier Transform (ISTFT)

InputNormalization

Performs mean and variance normalization of the input tensor.

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: torch.nn.modules.module.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: torch.nn.modules.module.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=1, log=False, eps=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: torch.nn.modules.module.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: torch.nn.modules.module.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: torch.nn.modules.module.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: torch.nn.modules.module.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: torch.nn.modules.module.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, torch.Tensor]
spk_dict_std: Dict[int, torch.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.