【问题标题】:How to automatically determine if there is NO seasonality from PSD/FFT of time series in python?如何自动确定python中时间序列的PSD / FFT是否没有季节性?
【发布时间】:2021-09-24 12:49:11
【问题描述】:

我有大约 1000 个不同的时间序列,对于每个时间序列,我想自动确定时间序列中是否存在任何季节性。

假设存在季节性,很容易从 FFT 或 PSD 确定周期性。

但是您如何根据 FFT 或 PSD 自动确定信号中没有季节性或周期性?

def psd_time_series(y):
   yAC = np.correlate(Y-np.mean(Y), Y-np.mean(Y), mode='full')
   yAC = yAC/np.max(yAC) # not necessary, but scales large values
   fft_yAC= np.fft.fft(yAC)
   freqs = np.arange(0,len(fft_yAC))/len(fft_yAC)
   psd = 10*np.log10(np.abs(fft_yAC)/max(np.abs(fft_yAC))
   return psd,freqs

def determine_if_seasonal(psd):
    ### part I need help with

def detect_seasonality(y):

   psd,freqs = psd_time_series(y)
  
   seasonality = ... #### do some check of PSD to determine if seasonal

   if seasonality:
       periodicity = round(1/freqs[psd.argsort()[::-1]][0])
   else:
       periodicity = None
   return periodicity

根据时间序列的 FFT 或 PSD 自动确定单个尖峰或高斯噪声不具有季节性的方法是什么? PSD 幅度的阈值是否有任何经验法则?峰的突出?峰高?

例如,单个尖峰的 PSD 图可能看起来像

单个尖峰的 FFT

或者高斯噪声的 PSD 可能看起来像

高斯噪声的FFT

或者具有周期性的实际信号的 PSD 可能看起来像

同一信号的FFT

感谢任何意见或见解。

【问题讨论】:

  • 我会投票结束这个问题,但我不能,因为它有赏金。在我看来,这似乎不是一个编程问题,而是一个关于信号处理的问题。想象一下,你要解决基本的概念信号处理问题——“我如何使用 FFT 来发现这种信号的(a)周期性?” ——真的还有什么问题吗?关于 Python 的部分似乎是切线的。也许signal processing stack exchange 很合适?
  • @gspr 也许你是对的,我想我不能取消赏金并关闭它?以前没用过赏金。
  • 不知道,抱歉。
  • 我认为赏金是non-refundable。如果我有时间,我可能会在一周内尝试给你一个答案。我现在可以说的是,只有当你有几个时期时,PSD 峰值才会明显。您是否可以对多个时期的数据进行抽样?

标签: python signal-processing fft


【解决方案1】:

这个答案附带一个免责声明,我在 15 年多的时间里不必进行这种类型的时间序列分析,因此我非常生疏了。我非常欢迎任何更正,因为我是凭记忆工作的,很可能忘记了一些事情。希望它可以让您了解我认为如果您的数据允许,您会如何做这样的事情,并且您可以改进该方法。 (如果你这样做,请回复或编辑答案!)

正如我在上面的评论中提到的,如果您可以将数据集分成多个部分,您就可以开始对数据集中不同频率的能量获得一些置信度限制。当然,这意味着您需要很长的数据集,这些数据集可能可用也可能不可用,具体取决于您在做什么。但就像任何统计技术一样,如果您没有大量数据,就很难对您的发现充满信心。我将继续描述我将如何确定存在信号,您可以将其反转以找到没有信号的位置。

我要做的第一件事是将数据集分成几个部分。您可以将其分解为多少取决于您的数据集相对于您尝试查找的信号的周期性(或在您的情况下未找到)的时间长短。要获得更多片段,您可以做的一件事是将它们重叠,但为了节省能量,您需要使用适当的窗口进行过滤。在下面的代码中,我假设有 50% 的重叠并应用 Hanning window。老实说,我忘记了不同窗口和重叠的细节,所以很抱歉,我无法提供更多信息来说明我为什么选择与这个窗口重叠。

希望从您的数据集中,您可以得出背景状态的分布或预期。也许它只是一个白噪声基底或更复杂的红移或蓝移。功率谱的背景水平应该为您提供有关噪声水平的信息,因为功率谱能量与噪声相关,如2 * noise**2 / (fs * L),其中fs 是采样频率,L 是窗口长度。如果我没记错就这些了,就像我说的我很生疏。

首先,让我们看一下噪声和噪声与信号叠加的功率谱。

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

def detrend(y):
    # This function removes the linear trend from the time series
    # by fitting y = mx + b to x and then subtracting it
    x = np.arange(len(y))
    A = np.vstack([x, np.ones(len(x))]).T
    m, b = np.linalg.lstsq(A, y, rcond=None)[0]
    return(y - m * x - b)

def subset(f, L, overlap, fs):
    # Break the function f into sections of length L.
    # Normally you do some overlapping of sections,
    # and you want to use an appropriate window
    # to conserve the energy in the time series signal.
    # Here I use a Hanning window.
    N = len(f)
    x = []
    for i in range(0, int(N-L+1), int(L * overlap)):
        window = np.hanning(L)
        y = detrend(f[i:i+L]) * window
        fft = np.fft.fft(y)
        fft = fft[:len(fft)//2+1]
        x.append(np.real(fft * np.conj(fft)) / (fs * L))
    return(x)

def noise(N):
    # Create a white noise field
    return(np.random.random(N) - 0.5)

N = 10**4 # length of time series
dt = 1    # sampling period
fs = 2 * np.pi / dt # sampling frequency
nyquist = fs / 2 # nyquist frequency
t = np.linspace(dt, N * dt, N) # times of data collection


L = N // 100 # window size used for subsampling
overlap = 0.5 # overlap in windows

# frequencies that will come out of the fft
# you can also use fp.fft.fftfreq and adjust
freqs = np.linspace(0, nyquist, L//2+1) 

# Create background white noise
noise_amplitude = 3
energy_scale = 2 * noise_amplitude**2 / (fs * L)
WhiteNoise = np.array(subset(noise_amplitude * noise(N), L, overlap, fs) ) / energy_scale

# Create another timeseries with a signal and noise
omega = 2 * np.pi / 10 # frequency in dataset
signal = (noise_amplitude / 4) * np.cos(t * omega)  # signal in dataset
data = signal + noise_amplitude * noise(N) # dataset
DataSet    = np.array(subset(data,  L, overlap, fs)) / energy_scale

# Percentiles of White Noise Power Spectra, for plotting
Wprct = np.percentile(WhiteNoise, [2.5, 25, 50, 75, 97.5], axis = 0)

# Percentiles of Data Power Spectra, for plotting
Dprct = np.percentile(DataSet, [2.5, 25, 50, 75, 97.5], axis = 0)

fig = plt.figure()
# Plot the spectra from all the subsets of the noise
for w in WhiteNoise:
    plt.semilogy(freqs[1:], w[1:], 'k', alpha = 0.05)

# Plot the median and confidence intervales
lines, = plt.semilogy(freqs[1:], Wprct[2,1:], label = 'Median of noise floor')
plt.fill_between(freqs[1:], Wprct[1,1:], Wprct[3,1:], alpha = 0.8, color = lines.get_color(), label = '50% CI of noise floor')
plt.fill_between(freqs[1:], Wprct[0,1:], Wprct[1,1:], alpha = 0.4, color = lines.get_color(), label = '95% CI of noise floor')
plt.fill_between(freqs[1:], Wprct[3,1:], Wprct[4,1:], alpha = 0.4, color = lines.get_color())

lines, = plt.plot(freqs[1:], Dprct[2,1:], label = 'Median signal-to-noise estimate')

plt.plot([omega, omega], [10**-3, 100], 'k:', label = 'Signal in dataset')
plt.plot([freqs[1], freqs[-1]], [1, 1], 'r:', label = 'Noise floor')
plt.legend()
 
plt.xlabel('Angular frequency')
plt.ylabel('Energy above noise floor [db]')

很明显,信号正在穿过噪音,但我认为我们可以找到比“目不转睛”更好的方法。在下面的代码中,我只查看“数据集”的每个频率上高于噪声分布并相应缩放的点数。从噪声中提取值有 50% 的机会使您的值大于噪声,因此 您希望您的信号远高于 50%。 (另一方面,如果该值小于 50%,则表明信号低于本底噪声,这会很有趣。)有 more advanced approaches,我没有进入这里,但我认为会给出相同的结果。

plt.figure()
for i in range(1, len(freqs)):
    x = 0
    for j in range(len(DataSet[:,i])):
        x += np.sum(DataSet[j,i] > WhiteNoise[:,i])
    x /= len(DataSet[:,i])**2
    plt.plot(freqs[i], x, 'k.')
plt.plot([omega, omega], [0.4, 1], 'k:', label = 'Signal in dataset')
plt.xlabel('Angular frequency')
plt.ylabel('Probability signal is greater than noise')
plt.legend()

我认为有人可以使用这些方法来说明不同频率的振荡在哪里,这应该可以解决您关于数据集季节性的问题。

【讨论】:

  • 同意@gspr 的观点,这更多是信号问题而不是编码问题,但也请阅读以上内容,您的赏金可能无法退还,我想给您一些东西。请仔细检查信号处理堆栈交换,以确保我没有误导您。
  • 看到第二个图的另一个想法。如果您查看有噪声的分布(徘徊在 0.5 左右)——我认为这是正常的——您可以开始估计信号频率附近的值是噪声的可能性。
【解决方案2】:

这是一个信号处理问题,但您可能想要计算功率谱密度,这可以使用scipy.signal 轻松完成,然后为总功率设置一个合理的阈值以分配周期性。

对于类似问题(不是我的)here

有更长的答案

【讨论】:

  • 是的,要添加到 eschibli 的信息和相关帖子,PSD 应该显示数据集中每个频率的能量。理想情况下,您的数据集应该足够长,您可以使用 Hanning 窗口之类的工具将它们切割成一些重叠的部分。这样你就可以整合你的时间序列并得到你的光谱能量的误差线。
【解决方案3】:

您可以使用自相关函数或部分自相关函数。您将获得每个滞后(周期)大小的系数,该系数将测量信号与其延迟版本的相似性。确保您使用大于某些周期(> 5)的滞后,并且如果所有系数都小于阈值(比如说,0.5,但我没有找到任何理论方法来支持这个决定),那么您的信号没有季节性.

【讨论】:

  • 如果你愿意,如果版主同意不删除/关闭问题,我可以添加代码自动制作。
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2018-06-01
相关资源
最近更新 更多