Skip to main content
 首页 » 编程设计

python之fft 功率谱问题

2025年02月15日10me-sa

我在从傅立叶变换中获取频谱时遇到问题...我有一些数据:

那个我以中庸为中心,似乎并没有太大的趋势...

我绘制了它的傅立叶变换:

我得到了一些不太好的东西......

这是我的代码:

def fourier_spectrum(X, sample_freq=1): 
    ps = np.abs(np.fft.fft(X))**2 
    freqs = np.fft.fftfreq(X.size, sample_freq) 
    idx = np.argsort(freqs) 
 
    plt.plot(freqs[idx], ps[idx]) 

改编自 here 中的代码.

它似乎适用于一些简单的正弦波数据:

fourier_spectrum(np.sin(2*np.pi*np.linspace(-10,10,400)), 20./400) 

所以我的问题是:我期待一个非零的几乎无处不在的频谱,我做错了什么?如果我没有做错任何事情,那么我的数据的哪些特征导致了这种情况?另外,如果我没有做错任何事情,而 fft 只是出于某种原因不适合我的数据,我应该怎么做才能从我的数据中提取重要的频率?

请您参考如下方法:

原来是我没看懂频谱中x轴的单位,就是Hz。因为我的采样间隔大约是一秒,而我的周期大约是一天,所以在我的频谱上唯一真正可见的单位是 ~1/s(在边缘)到大约 ~1/m(靠近中间),任何比它更长的周期都与 0 无法区分。我的误解源于 this 上的图表。教程,他们在那里进行转换,以便 x 轴单位及时,而不是反时限。我重写了我的 frequency_spectrum 绘图函数以对结果图进行适当的“缩放”...

def fourier_spectrum(X, sample_spacing_in_s=1, min_period_in_s=5): 
    ''' 
        X: is our data 
        sample_spacing_in_s: is the time spacing between samples 
        min_period_in_s: is the minimum period we want to show up in our 
            graph... this is handy because if our sample spacing is 
            small compared to the periods in our data, then our spikes 
            will all cluster near 0 (the infinite period) and we can't 
            see them.  E.g. if you want to see periods on the order of 
            days, set min_period_in_s=5*60*60 #5 hours 
    ''' 
    ps = np.abs(np.fft.fft(X))**2 
    freqs = np.fft.fftfreq(X.size, sample_spacing_in_s) 
    idx = np.argsort(freqs) 
    plt.plot(freqs[idx], ps[idx]) 
    plt.xlim(-1./min_period_in_s,1./min_period_in_s) # the x-axis is in Hz