stoi.py 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Copyright The Lightning team.
  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. import numpy as np
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.utilities.checks import _check_same_shape
  18. from torchmetrics.utilities.imports import _PYSTOI_AVAILABLE
  19. if not _PYSTOI_AVAILABLE:
  20. __doctest_skip__ = ["short_time_objective_intelligibility"]
  21. def short_time_objective_intelligibility(
  22. preds: Tensor, target: Tensor, fs: int, extended: bool = False, keep_same_device: bool = False
  23. ) -> Tensor:
  24. r"""Calculate STOI (Short-Time Objective Intelligibility) metric for evaluating speech signals.
  25. Intelligibility measure which is highly correlated with the intelligibility of degraded speech signals, e.g., due to
  26. additive noise, single-/multi-channel noise reduction, binary masking and vocoded speech as in CI simulations. The
  27. STOI-measure is intrusive, i.e., a function of the clean and degraded speech signals. STOI may be a good alternative
  28. to the speech intelligibility index (SII) or the speech transmission index (STI), when you are interested in
  29. the effect of nonlinear processing to noisy speech, e.g., noise reduction, binary masking algorithms, on speech
  30. intelligibility. Description taken from `Cees Taal's website`_ and for further details see `STOI ref1`_ and
  31. `STOI ref2`_.
  32. This metric is a wrapper for the `pystoi package`_. As the implementation backend implementation only supports
  33. calculations on CPU, all input will automatically be moved to CPU to perform the metric calculation before being
  34. moved back to the original device.
  35. .. hint::
  36. Usingsing this metrics requires you to have ``pystoi`` install. Either install as ``pip install
  37. torchmetrics[audio]`` or ``pip install pystoi``
  38. Args:
  39. preds: float tensor with shape ``(...,time)``
  40. target: float tensor with shape ``(...,time)``
  41. fs: sampling frequency (Hz)
  42. extended: whether to use the extended STOI described in `STOI ref3`_.
  43. keep_same_device: whether to move the stoi value to the device of preds
  44. Returns:
  45. stoi value of shape [...]
  46. Raises:
  47. ModuleNotFoundError:
  48. If ``pystoi`` package is not installed
  49. RuntimeError:
  50. If ``preds`` and ``target`` does not have the same shape
  51. Example:
  52. >>> from torch import randn
  53. >>> from torchmetrics.functional.audio.stoi import short_time_objective_intelligibility
  54. >>> preds = randn(8000)
  55. >>> target = randn(8000)
  56. >>> short_time_objective_intelligibility(preds, target, 8000).float()
  57. tensor(-0.084...)
  58. """
  59. if not _PYSTOI_AVAILABLE:
  60. raise ModuleNotFoundError(
  61. "ShortTimeObjectiveIntelligibility metric requires that `pystoi` is installed."
  62. " Either install as `pip install torchmetrics[audio]` or `pip install pystoi`."
  63. )
  64. from pystoi import stoi as stoi_backend
  65. _check_same_shape(preds, target)
  66. if len(preds.shape) == 1:
  67. stoi_val_np = stoi_backend(target.detach().cpu().numpy(), preds.detach().cpu().numpy(), fs, extended)
  68. stoi_val = torch.tensor(stoi_val_np)
  69. else:
  70. preds_np = preds.reshape(-1, preds.shape[-1]).detach().cpu().numpy()
  71. target_np = target.reshape(-1, preds.shape[-1]).detach().cpu().numpy()
  72. stoi_val_np = np.empty(shape=(preds_np.shape[0]))
  73. for b in range(preds_np.shape[0]):
  74. stoi_val_np[b] = stoi_backend(target_np[b, :], preds_np[b, :], fs, extended)
  75. stoi_val = torch.from_numpy(stoi_val_np)
  76. stoi_val = stoi_val.reshape(preds.shape[:-1])
  77. if keep_same_device:
  78. return stoi_val.to(preds.device)
  79. return stoi_val