且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测时间序列中的给定模式

更新时间:2023-02-26 15:45:42

There are many ways to do this. I will show one of the fastest and simplest way. It is based on using correlation.

First of all we need a data(time series) and template(in our case the template is like a signum function):

data = np.concatenate([np.random.rand(70),np.random.rand(30)+2])
template = np.concatenate([[-1]*5,[1]*5])

Before detection I strongly recommend normalize the data(for example like that):

data = (data - data.mean())/data.std()

And now all we need is use of correlation function:

corr_res = np.correlate(data, template,mode='same')

You need to choose the threshold for results(you should define that value based on your template):

th = 9

You can see the results:

plt.figure(figsize=(10,5))
plt.subplot(211)
plt.plot(data)
plt.subplot(212)
plt.plot(corr_res)
plt.plot(np.arange(len(corr_res))[corr_res > th],corr_res[corr_res > th],'ro')
plt.show()