Smoothed Z-score Algorithm
簡介
時序異常檢測,可以檢測實時時間序列數據中的峰值信號並且平滑數據數據的一種算法,說人話就是找出數據的異常突變點並且同時平滑曲線,線性O(n)復雜度
原理
利用數據均值(mean)和標准差(std)來判斷數據是否為異常值
算法具體實現:使用一個長度為lag
的滑動窗口,在這個窗口中計算窗口中的均值filter_avg
和標准差filter_std
,然后根據參數threshold
將數據和平均值、方差做比較,最后利用influence
平滑曲線(influence
越大,原數據影響越大,曲線越不平滑)
代碼實現
# Python3
# Created by Santiego
def smooth_data_and_find_peak(data_raw, lag, threshold, influence=0.5):
# Smoothed Z-Score Algorithm
res_peak = []
res_data_smoothed = data_raw
filter_avg = np.zeros(256)
filter_std = np.zeros(256)
filter_avg[lag - 1] = np.mean(data_raw[0: lag])
filter_std[lag - 1] = np.std(data_raw[0: lag])
for i in range(lag, 255):
if abs(data_raw[i] - filter_avg[i - 1]) > threshold * filter_std[i - 1]:
if data_raw[i] > filter_avg[i-1]:
res_peak.append(i)
res_data_smoothed[i] = influence * data_raw[i] + (1-influence) * res_data_smoothed[i-1]
filter_avg[i] = np.mean(res_data_smoothed[(i - lag): i])
filter_std[i] = np.std(res_data_smoothed[(i - lag): i])
else:
res_data_smoothed[i] = data_raw[i]
filter_avg[i] = np.mean(res_data_smoothed[(i - lag):i])
filter_std[i] = np.std(res_data_smoothed[(i - lag):i])
return res_peak, res_data_smoothed
注意
需要調參,而且算法只是為了尋找數據異常突變點,不能尋找大趨勢,也就是說不能很好的尋找到數據的峰值(理論和實際測試)