|
| 1 | +# ------------------------------------------------------------------------ # |
| 2 | +# Copyright 2022 SPTK Working Group # |
| 3 | +# # |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); # |
| 5 | +# you may not use this file except in compliance with the License. # |
| 6 | +# You may obtain a copy of the License at # |
| 7 | +# # |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 # |
| 9 | +# # |
| 10 | +# Unless required by applicable law or agreed to in writing, software # |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, # |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # |
| 13 | +# See the License for the specific language governing permissions and # |
| 14 | +# limitations under the License. # |
| 15 | +# ------------------------------------------------------------------------ # |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | +from ..typing import Precomputed |
| 20 | +from ..utils.private import UNVOICED_SYMBOL, filter_values |
| 21 | +from .base import BaseFunctionalModule |
| 22 | +from .rmse import RootMeanSquareError |
| 23 | + |
| 24 | + |
| 25 | +class F0Evaluation(BaseFunctionalModule): |
| 26 | + """See `this page <https://sp-nitech.github.io/sptk/latest/main/f0eval.html>`_ |
| 27 | + for details. Note that the gradients cannot be calculated if the output format |
| 28 | + is related to voiced/unvoiced decision. |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + reduction : ['none', 'mean', 'sum'] |
| 33 | + The reduction type. |
| 34 | +
|
| 35 | + out_format : ['f0-rmse-hz', 'f0-rmse-cent', 'f0-rmse-semitone', 'vuv-error-rate', \ |
| 36 | + 'vuv-error-percent', 'vuv-macro-f1-score'] |
| 37 | + The output format. |
| 38 | +
|
| 39 | + """ |
| 40 | + |
| 41 | + def __init__( |
| 42 | + self, reduction: str = "mean", out_format: str = "f0-rmse-cent" |
| 43 | + ) -> None: |
| 44 | + super().__init__() |
| 45 | + |
| 46 | + self.values = self._precompute(**filter_values(locals())) |
| 47 | + |
| 48 | + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: |
| 49 | + """Calculate F0 metric. |
| 50 | +
|
| 51 | + Parameters |
| 52 | + ---------- |
| 53 | + x : Tensor [shape=(..., N)] |
| 54 | + The input F0 in Hz. |
| 55 | +
|
| 56 | + y : Tensor [shape=(..., N)] |
| 57 | + The target F0 in Hz. |
| 58 | +
|
| 59 | + Returns |
| 60 | + ------- |
| 61 | + out : Tensor [shape=(...,) or scalar] |
| 62 | + The F0 metric. |
| 63 | +
|
| 64 | + """ |
| 65 | + return self._forward(x, y, *self.values) |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def _func(x: torch.Tensor, y: torch.Tensor, *args, **kwargs) -> torch.Tensor: |
| 69 | + values = F0Evaluation._precompute(*args, **kwargs) |
| 70 | + return F0Evaluation._forward(x, y, *values) |
| 71 | + |
| 72 | + @staticmethod |
| 73 | + def _takes_input_size() -> bool: |
| 74 | + return False |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def _check() -> None: |
| 78 | + pass |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def _precompute(reduction: str, out_format: str) -> Precomputed: |
| 82 | + F0Evaluation._check() |
| 83 | + return (reduction, out_format) |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def _forward( |
| 87 | + x: torch.Tensor, y: torch.Tensor, reduction: str, out_format: str |
| 88 | + ) -> torch.Tensor: |
| 89 | + if out_format.startswith("f0-rmse"): |
| 90 | + voiced = (x != UNVOICED_SYMBOL) & (y != UNVOICED_SYMBOL) |
| 91 | + if out_format == "f0-rmse-hz": |
| 92 | + convert = lambda x: x |
| 93 | + elif out_format == "f0-rmse-cent": |
| 94 | + convert = lambda x: 1200 * torch.log2(x) |
| 95 | + elif out_format == "f0-rmse-semitone": |
| 96 | + convert = lambda x: 12 * torch.log2(x) |
| 97 | + else: |
| 98 | + raise ValueError(f"out_format {out_format} is not supported.") |
| 99 | + out = RootMeanSquareError._func( |
| 100 | + convert(x[voiced]), convert(y[voiced]), "none" |
| 101 | + ) |
| 102 | + else: |
| 103 | + TP = torch.sum((x != UNVOICED_SYMBOL) & (y != UNVOICED_SYMBOL), dim=-1) |
| 104 | + FP = torch.sum((x == UNVOICED_SYMBOL) & (y != UNVOICED_SYMBOL), dim=-1) |
| 105 | + FN = torch.sum((x != UNVOICED_SYMBOL) & (y == UNVOICED_SYMBOL), dim=-1) |
| 106 | + TN = torch.sum((x == UNVOICED_SYMBOL) & (y == UNVOICED_SYMBOL), dim=-1) |
| 107 | + FPFN = FP + FN |
| 108 | + if out_format == "vuv-error-rate": |
| 109 | + out = FPFN / x.shape[-1] |
| 110 | + elif out_format == "vuv-error-percent": |
| 111 | + out = 100 * FPFN / x.shape[-1] |
| 112 | + elif out_format == "vuv-macro-f1-score": |
| 113 | + f1_score_pos = torch.nan_to_num((2 * TP) / (2 * TP + FPFN)) |
| 114 | + f1_score_neg = torch.nan_to_num((2 * TN) / (2 * TN + FPFN)) |
| 115 | + out = (f1_score_pos + f1_score_neg) / 2 |
| 116 | + else: |
| 117 | + raise ValueError(f"out_format {out_format} is not supported.") |
| 118 | + |
| 119 | + if reduction == "none": |
| 120 | + pass |
| 121 | + elif reduction == "sum": |
| 122 | + out = out.sum() |
| 123 | + elif reduction == "mean": |
| 124 | + out = out.mean() |
| 125 | + else: |
| 126 | + raise ValueError(f"reduction {reduction} is not supported.") |
| 127 | + |
| 128 | + return out |
0 commit comments