# Calculate Signal to Noise ratio in Python

Hello, welcome. Here you are going to learn how to Calculate Signal to Noise ratio in Python using SciPy.

First, let’s know what is Signal to noise ratio (SNR). It is the resultant of mean divided by the standard deviation.

Using the SciPy library, we shall be able to find it. SciPy library has a sub-package known as statistics (stats) which contains a signal to noise() function that simply finds the value which we were looking for.

To learn more about the SciPy library and a few of its sub-packages, Click on the below link.

Learn about some of the Special sub-package of Scipy Python module

## Python program to calculate Signal to Noise ratio

Now let’s look into the code that finds the SNR. Below is our Python program:

import numpy as np from scipy import stats array1 = [[20, 4, 7, 1, 34], [50, 12, 15, 34, 5]] array2 = [50, 12, 15, 34, 5] print ("signaltonoise ratio for array1: ", stats.signaltonoise(array1, axis = 0, ddof = 0)) print ("signaltonoise ratio for array1 : ", stats.signaltonoise(array1, axis = 1, ddof = 0)) print ("\nsignaltonoise ratio for array2 : ", stats.signaltonoise(array2, axis = 0, ddof = 0))

Let’s understand what the above code does.

We have imported the NumPy module as np. Since we need the statistics module, we have imported from the SciPy library. We have declared two arrays to find out the SNR.

In the print statement, we have invoked the signaltonoise() function.

**OUTPUT FOR THE ABOVE CODE :**

signaltonoise ratio for array1: [2.33333333 2. 2.75 1.06060606 1.34482759] signaltonoise ratio for array1: [1.07720113 1.40732764] signaltonoise ratio for array2: 1.407327642072067

In the above output, we can see the SNR for the arrays that we have declared.

The SignalToNoise Ratio function takes 3 Parameters :

1st is the NumPy array, containing the sample data.

2nd is the axis along which the mean can be calculated, Its default value is 0.

and 3rd is the degree of freedom which is a correction to the standard deviation.

This function returns an array as an output as we have seen in the above example.

To know the implementation of the SignaltoNoise Ratio, Take a look at the following code:

import numpy as np def signaltonoise(Arr, axis=0, ddof=0): Arr = np.asanyarray(Arr) me = Arr.mean(axis) sd = Arr.std(axis=axis, ddof=ddof) return np.where(sd == 0, 0, me/sd) Arr=[[20, 4, 7, 1, 34], [50, 12, 15, 34, 5]] print(signaltonoise(Arr,axis=0,ddof=0))

OUTPUT:

[2.33333333 2. 2.75 1.06060606 1.34482759]

In the above implementation, we can see how the mean and standard deviation whose division gives us the required output is being measured. The standard deviation value is taken as Zero.

## Leave a Reply

You must be logged in to post a comment.