Skip to content

snr

SNR Metrics API

Signal-to-Noise Ratio (SNR) metric where y_true: signal, y_pred: signal + noise

Classes:

  • Snr

    Computes the Signal-to-Noise Ratio (SNR) in dB.

Classes

Snr

Snr(name='snr', **kwargs)

Signal-to-Noise Ratio (SNR) metric where y_true: signal y_pred: signal + noise

Parameters:

  • name (str, default: 'snr' ) –

    Name of the metric. Defaults to 'snr'.

Example:

# Create 4-second sine wave w/ freq=4, amplitude=1, Fs=1000Hz
t = np.linspace(0, 4, 4 * 1000, endpoint=False)
x = np.sin(2 * np.pi * 4 * t)
# Add random noise with amplitude 0.1
noise = np.random.normal(0, 0.1, len(t))
y = x + noise
snr = nse.metrics.Snr()
snr.update_state(x, y)
print(snr.result())
Source code in neuralspot_edge/metrics/snr.py
def __init__(self, name="snr", **kwargs):
    """Signal-to-Noise Ratio (SNR) metric where
        y_true: signal
        y_pred: signal + noise

    Args:
        name (str, optional): Name of the metric. Defaults to 'snr'.

    Example:

    ```python
    # Create 4-second sine wave w/ freq=4, amplitude=1, Fs=1000Hz
    t = np.linspace(0, 4, 4 * 1000, endpoint=False)
    x = np.sin(2 * np.pi * 4 * t)
    # Add random noise with amplitude 0.1
    noise = np.random.normal(0, 0.1, len(t))
    y = x + noise
    snr = nse.metrics.Snr()
    snr.update_state(x, y)
    print(snr.result())
    ```
    """
    super().__init__(name=name, **kwargs)
    self.num = self.add_variable(shape=(), initializer="zeros", name="num")
    self.den = self.add_variable(shape=(), initializer="zeros", name="den")

Functions

result
result()

Computes the SNR in dB.

Source code in neuralspot_edge/metrics/snr.py
def result(self):
    """Computes the SNR in dB."""
    ratio = keras.ops.divide(self.num, self.den + keras.backend.epsilon())
    ratio = keras.ops.convert_to_tensor(ratio, dtype=self.dtype)
    snr = 10 * keras.ops.log10(ratio + keras.backend.epsilon())
    return snr  # in dB