Search code examples
pythonscipysignal-processing

how to calculate signal to noise ratio using python


Dear experts i have a data set.i just want to calculate signal to noise ratio of the data. data is loaded here https://i.fluffy.cc/jwg9d7nRNDFqdzvg1Qthc0J7CNtKd5CV.html

my code is given below:

import numpy as np
from scipy import signaltonoise
import scipy.io
dat=scipy.io.loadmat('./data.mat')
arr=dat['dn']
snr=scipy.stats.signaltonoise(arr, axis=0, ddof=0) 

but i am getting error like importError: cannot import name 'signaltonoise' from 'scipy' if it doesn't exist how to calculate snr,please suggest some other way to do it with this data set using python.


Solution

  • scipy.stats.signaltonoise was removed in scipy 1.0.0. You can either downgrade your scipy version or create the function yourself:

    def signaltonoise(a, axis=0, ddof=0):
        a = np.asanyarray(a)
        m = a.mean(axis)
        sd = a.std(axis=axis, ddof=ddof)
        return np.where(sd == 0, 0, m/sd)
    

    Source: https://github.com/scipy/scipy/blob/v0.16.0/scipy/stats/stats.py#L1963

    See the github link for the docstring.

    Edit: the full script would then look as follows

    import numpy as np
    import scipy.io
    
    def signaltonoise(a, axis=0, ddof=0):
        a = np.asanyarray(a)
        m = a.mean(axis)
        sd = a.std(axis=axis, ddof=ddof)
        return np.where(sd == 0, 0, m/sd)
    
    dat = scipy.io.loadmat('./data.mat')
    arr = dat['dn']
    snr = signaltonoise(arr)