周期图查找时间序列的季节

问题描述 投票:0回答:1

我有一个时间序列正在检测一个切换系统,该系统具有长度为 k 的重复模式,其中 (k-1) 个连续值为 0 并且 1 等于 1。我想使用周期图来查找该系统的长度 k系统。我怎样才能做到这一点?

目前我有这个代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import periodogram

def find_repetitive_pattern_length(time_series):
    f, Pxx = periodogram(time_series)
    max_power_index = np.argmax(Pxx)
    dominant_frequency = f[max_power_index]
    period_length = int(1 / dominant_frequency)

    
    plt.figure(figsize=(10, 6))
    plt.plot(f, Pxx, label='Periodogram')
    plt.scatter(f[max_power_index], Pxx[max_power_index], color='red', label=f'Dominant Frequency: {dominant_frequency:.2f} Hz')
    plt.title('Periodogram with Dominant Frequency')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Power/Frequency Density')
    plt.legend()
    plt.show()

    return period_length


time_series4 = np.array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1])
time_series7 = np.array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1])
period_length = find_repetitive_pattern_length(time_series4)
print(f"The length of the first repetitive pattern is: {period_length}")
period_length = find_repetitive_pattern_length(time_series7)
print(f"The length of the second repetitive pattern is: {period_length}")

但我明白:

第一个重复模式的长度是:4(正确)

第二个重复模式的长度是:3(不正确)

我做错了什么以及如何解决?

python numpy scipy time-series pattern-recognition
1个回答
0
投票

这是一个我相信可以解决您的问题的解决方案,但不使用周期图。函数

get_season
接受一个 numpy 数组
arr
并返回
arr
中的距离的众数。

import numpy as np

time_series4 = np.array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1])
time_series7 = np.array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1])

def get_season(arr):
    """
    returns the most common difference between indices of adjacent non-zero values in arr
    """
    return np.argmax(np.bincount(np.diff(np.where(arr)[0])))

assert get_season(time_series4) == 4
assert get_season(time_series7) == 7
© www.soinside.com 2019 - 2024. All rights reserved.