MCPcopy Create free account
hub / github.com/ddbourgin/numpy-ml / to_frames

Function to_frames

numpy_ml/preprocessing/dsp.py:354–413  ·  view source on GitHub ↗

Convert a 1D signal x into overlapping windows of width `frame_width` using a hop length of `stride`. Notes ----- If ``(len(x) - frame_width) % stride != 0`` then some number of the samples in x will be dropped. Specifically:: n_dropped_frames = len(x) - frame_widt

(x, frame_width, stride, writeable=False)

Source from the content-addressed store, hash-verified

352
353
354def to_frames(x, frame_width, stride, writeable=False):
355 """
356 Convert a 1D signal x into overlapping windows of width `frame_width` using
357 a hop length of `stride`.
358
359 Notes
360 -----
361 If ``(len(x) - frame_width) % stride != 0`` then some number of the samples
362 in x will be dropped. Specifically::
363
364 n_dropped_frames = len(x) - frame_width - stride * (n_frames - 1)
365
366 where::
367
368 n_frames = (len(x) - frame_width) // stride + 1
369
370 This method uses low-level stride manipulation to avoid creating an
371 additional copy of `x`. The downside is that if ``writeable`=True``,
372 modifying the `frame` output can result in unexpected behavior:
373
374 >>> out = to_frames(np.arange(6), 5, 1)
375 >>> out
376 array([[0, 1, 2, 3, 4],
377 [1, 2, 3, 4, 5]])
378 >>> out[0, 1] = 99
379 >>> out
380 array([[ 0, 99, 2, 3, 4],
381 [99, 2, 3, 4, 5]])
382
383 Parameters
384 ----------
385 x : :py:class:`ndarray <numpy.ndarray>` of shape `(N,)`
386 A 1D signal consisting of N samples
387 frame_width : int
388 The width of a single frame window in samples
389 stride : int
390 The hop size / number of samples advanced between consecutive frames
391 writeable : bool
392 If set to False, the returned array will be readonly. Otherwise it will
393 be writable if `x` was. It is advisable to set this to False whenever
394 possible to avoid unexpected behavior (see NB 2 above). Default is False.
395
396 Returns
397 -------
398 frame: :py:class:`ndarray <numpy.ndarray>` of shape `(n_frames, frame_width)`
399 The collection of overlapping frames stacked into a matrix
400 """
401 assert x.ndim == 1
402 assert stride >= 1
403 assert len(x) >= frame_width
404
405 # get the size for an element in x in bits
406 byte = x.itemsize
407 n_frames = (len(x) - frame_width) // stride + 1
408 return as_strided(
409 x,
410 shape=(n_frames, frame_width),
411 strides=(byte * stride, byte),

Callers 2

test_framingFunction · 0.90
mel_spectrogramFunction · 0.85

Calls

no outgoing calls

Tested by 1

test_framingFunction · 0.72