mel_features.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # Copyright 2017 The TensorFlow Authors All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Defines routines to compute mel spectrogram features from audio waveform."""
  16. import numpy as np
  17. def frame(data, window_length, hop_length):
  18. """Convert array into a sequence of successive possibly overlapping frames.
  19. An n-dimensional array of shape (num_samples, ...) is converted into an
  20. (n+1)-D array of shape (num_frames, window_length, ...), where each frame
  21. starts hop_length points after the preceding one.
  22. This is accomplished using stride_tricks, so the original data is not
  23. copied. However, there is no zero-padding, so any incomplete frames at the
  24. end are not included.
  25. Args:
  26. data: np.array of dimension N >= 1.
  27. window_length: Number of samples in each frame.
  28. hop_length: Advance (in samples) between each window.
  29. Returns:
  30. (N+1)-D np.array with as many rows as there are complete frames that can be
  31. extracted.
  32. """
  33. num_samples = data.shape[0]
  34. num_frames = 1 + int(np.floor((num_samples - window_length) / hop_length))
  35. shape = (num_frames, window_length) + data.shape[1:]
  36. strides = (data.strides[0] * hop_length,) + data.strides
  37. return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides)
  38. def periodic_hann(window_length):
  39. """Calculate a "periodic" Hann window.
  40. The classic Hann window is defined as a raised cosine that starts and
  41. ends on zero, and where every value appears twice, except the middle
  42. point for an odd-length window. Matlab calls this a "symmetric" window
  43. and np.hanning() returns it. However, for Fourier analysis, this
  44. actually represents just over one cycle of a period N-1 cosine, and
  45. thus is not compactly expressed on a length-N Fourier basis. Instead,
  46. it's better to use a raised cosine that ends just before the final
  47. zero value - i.e. a complete cycle of a period-N cosine. Matlab
  48. calls this a "periodic" window. This routine calculates it.
  49. Args:
  50. window_length: The number of points in the returned window.
  51. Returns:
  52. A 1D np.array containing the periodic hann window.
  53. """
  54. return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
  55. np.arange(window_length)))
  56. def stft_magnitude(signal, fft_length,
  57. hop_length=None,
  58. window_length=None):
  59. """Calculate the short-time Fourier transform magnitude.
  60. Args:
  61. signal: 1D np.array of the input time-domain signal.
  62. fft_length: Size of the FFT to apply.
  63. hop_length: Advance (in samples) between each frame passed to FFT.
  64. window_length: Length of each block of samples to pass to FFT.
  65. Returns:
  66. 2D np.array where each row contains the magnitudes of the fft_length/2+1
  67. unique values of the FFT for the corresponding frame of input samples.
  68. """
  69. frames = frame(signal, window_length, hop_length)
  70. # Apply frame window to each frame. We use a periodic Hann (cosine of period
  71. # window_length) instead of the symmetric Hann of np.hanning (period
  72. # window_length-1).
  73. window = periodic_hann(window_length)
  74. windowed_frames = frames * window
  75. return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))
  76. # Mel spectrum constants and functions.
  77. _MEL_BREAK_FREQUENCY_HERTZ = 700.0
  78. _MEL_HIGH_FREQUENCY_Q = 1127.0
  79. def hertz_to_mel(frequencies_hertz):
  80. """Convert frequencies to mel scale using HTK formula.
  81. Args:
  82. frequencies_hertz: Scalar or np.array of frequencies in hertz.
  83. Returns:
  84. Object of same size as frequencies_hertz containing corresponding values
  85. on the mel scale.
  86. """
  87. return _MEL_HIGH_FREQUENCY_Q * np.log(
  88. 1.0 + (frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ))
  89. def spectrogram_to_mel_matrix(num_mel_bins=20,
  90. num_spectrogram_bins=129,
  91. audio_sample_rate=8000,
  92. lower_edge_hertz=125.0,
  93. upper_edge_hertz=3800.0):
  94. """Return a matrix that can post-multiply spectrogram rows to make mel.
  95. Returns a np.array matrix A that can be used to post-multiply a matrix S of
  96. spectrogram values (STFT magnitudes) arranged as frames x bins to generate a
  97. "mel spectrogram" M of frames x num_mel_bins. M = S A.
  98. The classic HTK algorithm exploits the complementarity of adjacent mel bands
  99. to multiply each FFT bin by only one mel weight, then add it, with positive
  100. and negative signs, to the two adjacent mel bands to which that bin
  101. contributes. Here, by expressing this operation as a matrix multiply, we go
  102. from num_fft multiplies per frame (plus around 2*num_fft adds) to around
  103. num_fft^2 multiplies and adds. However, because these are all presumably
  104. accomplished in a single call to np.dot(), it's not clear which approach is
  105. faster in Python. The matrix multiplication has the attraction of being more
  106. general and flexible, and much easier to read.
  107. Args:
  108. num_mel_bins: How many bands in the resulting mel spectrum. This is
  109. the number of columns in the output matrix.
  110. num_spectrogram_bins: How many bins there are in the source spectrogram
  111. data, which is understood to be fft_size/2 + 1, i.e. the spectrogram
  112. only contains the nonredundant FFT bins.
  113. audio_sample_rate: Samples per second of the audio at the input to the
  114. spectrogram. We need this to figure out the actual frequencies for
  115. each spectrogram bin, which dictates how they are mapped into mel.
  116. lower_edge_hertz: Lower bound on the frequencies to be included in the mel
  117. spectrum. This corresponds to the lower edge of the lowest triangular
  118. band.
  119. upper_edge_hertz: The desired top edge of the highest frequency band.
  120. Returns:
  121. An np.array with shape (num_spectrogram_bins, num_mel_bins).
  122. Raises:
  123. ValueError: if frequency edges are incorrectly ordered or out of range.
  124. """
  125. nyquist_hertz = audio_sample_rate / 2.
  126. if lower_edge_hertz < 0.0:
  127. raise ValueError("lower_edge_hertz %.1f must be >= 0" % lower_edge_hertz)
  128. if lower_edge_hertz >= upper_edge_hertz:
  129. raise ValueError("lower_edge_hertz %.1f >= upper_edge_hertz %.1f" %
  130. (lower_edge_hertz, upper_edge_hertz))
  131. if upper_edge_hertz > nyquist_hertz:
  132. raise ValueError("upper_edge_hertz %.1f is greater than Nyquist %.1f" %
  133. (upper_edge_hertz, nyquist_hertz))
  134. spectrogram_bins_hertz = np.linspace(0.0, nyquist_hertz, num_spectrogram_bins)
  135. spectrogram_bins_mel = hertz_to_mel(spectrogram_bins_hertz)
  136. # The i'th mel band (starting from i=1) has center frequency
  137. # band_edges_mel[i], lower edge band_edges_mel[i-1], and higher edge
  138. # band_edges_mel[i+1]. Thus, we need num_mel_bins + 2 values in
  139. # the band_edges_mel arrays.
  140. band_edges_mel = np.linspace(hertz_to_mel(lower_edge_hertz),
  141. hertz_to_mel(upper_edge_hertz), num_mel_bins + 2)
  142. # Matrix to post-multiply feature arrays whose rows are num_spectrogram_bins
  143. # of spectrogram values.
  144. mel_weights_matrix = np.empty((num_spectrogram_bins, num_mel_bins))
  145. for i in range(num_mel_bins):
  146. lower_edge_mel, center_mel, upper_edge_mel = band_edges_mel[i:i + 3]
  147. # Calculate lower and upper slopes for every spectrogram bin.
  148. # Line segments are linear in the *mel* domain, not hertz.
  149. lower_slope = ((spectrogram_bins_mel - lower_edge_mel) /
  150. (center_mel - lower_edge_mel))
  151. upper_slope = ((upper_edge_mel - spectrogram_bins_mel) /
  152. (upper_edge_mel - center_mel))
  153. # .. then intersect them with each other and zero.
  154. mel_weights_matrix[:, i] = np.maximum(0.0, np.minimum(lower_slope,
  155. upper_slope))
  156. # HTK excludes the spectrogram DC bin; make sure it always gets a zero
  157. # coefficient.
  158. mel_weights_matrix[0, :] = 0.0
  159. return mel_weights_matrix
  160. def log_mel_spectrogram(data,
  161. audio_sample_rate=8000,
  162. log_offset=0.0,
  163. window_length_secs=0.025,
  164. hop_length_secs=0.010,
  165. **kwargs):
  166. """Convert waveform to a log magnitude mel-frequency spectrogram.
  167. Args:
  168. data: 1D np.array of waveform data.
  169. audio_sample_rate: The sampling rate of data.
  170. log_offset: Add this to values when taking log to avoid -Infs.
  171. window_length_secs: Duration of each window to analyze.
  172. hop_length_secs: Advance between successive analysis windows.
  173. **kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.
  174. Returns:
  175. 2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank
  176. magnitudes for successive frames.
  177. """
  178. window_length_samples = int(round(audio_sample_rate * window_length_secs))
  179. hop_length_samples = int(round(audio_sample_rate * hop_length_secs))
  180. fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0)))
  181. spectrogram = stft_magnitude(
  182. data,
  183. fft_length=fft_length,
  184. hop_length=hop_length_samples,
  185. window_length=window_length_samples)
  186. mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix(
  187. num_spectrogram_bins=spectrogram.shape[1],
  188. audio_sample_rate=audio_sample_rate, **kwargs))
  189. return np.log(mel_spectrogram + log_offset)