【问题标题】:Recurrence plot in pythonpython中的递归图
【发布时间】:2016-02-12 12:48:20
【问题描述】:

我正在尝试按照我的要求对时间序列中的模式进行聚类

How to clustering syllable types with python?

我尝试使用递归图技术来解决我的问题,所以我在 python 中编写了一些代码来重现这些图。我想知道我的代码是否正常,我尝试了一个合理的时间序列,我得到的结果取决于距离参数值:

http://ceciliajarne.web.unq.edu.ar/envelope-problem/

我还包括数据集。我正在使用 ch2。这是我的代码:

import numpy as np
import scipy
import os

from scipy.io import wavfile
import wave, struct
import matplotlib.pyplot as pp

from pylab import *

import scipy.signal.signaltools as sigtool
import scipy, pylab
from scipy.io import wavfile
import wave, struct
import scipy.signal as signal
from scipy.fftpack import fft

 #Data set input
data=np.random.rand(44000*3) 
#random secuence to compare with almost 3 seconds of data, cold be other
print 'data:', data

#set size 
sissse=data.size
print 'size: ',sissse
print '---------------'

#empty vectors 

x_filt_all_p=[]
y_filt_all_p=[]
los_p_filt_all_p=[]

#creating the list to fill 
dif=[]
dif_abs=[]
p=1

#for each i-element of data vector for each p

for p in range(1,sissse,4400):
    for i in enumerate(data):
        #print i
        j=i[0]
        #print 'j: ',j
        if (j<sissse-p):
            dif_aux=data[j+p]-data[j]
            #print 'dif=',dif_aux
            dif.append(dif_aux)
                dif_abs.append(abs(data[j+p]-data[j]))      
            #print'.........'

    print'.........'
    #print 'dif=',dif
    print'.........'
    #print 'Absolute difference=',dif_abs
    print'.........'

    #vector with index and diferences in absolute value

    pepe= np.vstack([np.arange(len(dif_abs)),dif_abs])

    print 'pepe0: ', pepe[0]
    xx=pepe[0]
    print 'pepe1: ', pepe[1]
    yy=pepe[1]

    #filtering the elements with diference<delta

    delta= 0.001

    # Now let's extract only the part of the data we're interested in...

    los_p = np.empty(len(pepe[1]))#dif_abs
    los_p.fill(p)

    x_filt    = xx[yy<delta]
    y_filt    = yy[yy<delta] 
    los_p_filt= los_p[yy<delta]

    print 'value of coordinate i', x_filt
    print 'absolute difference', y_filt 
    print 'value of coordinate p', los_p_filt
    print '------------------------'
    if (p==1):
        x_filt_all_p=x_filt
        y_filt_all_p=y_filt
        los_p_filt_all_p=los_p_filt
    else:
        x_filt_all_p=np.concatenate((x_filt_all_p,x_filt)) 
        y_filt_all_p=np.concatenate((y_filt_all_p,y_filt))
        los_p_filt_all_p=np.concatenate((los_p_filt_all_p,los_p_filt))

print 'full value of coordinate i: ', x_filt_all_p
print 'full absolute difference', y_filt_all_p 
print 'full value of coordinate p: ', los_p_filt_all_p

#trying to plot the "recurrence plots" together with the envelope.

pp.subplot(211)
pp.plot(arange(data.size),data, color='c',label='Time Signal 2')
pp.legend(fontsize= 'small')
pp.grid(True)
pp.xlabel('Time (s)')
pp.ylabel('Amplitude')  
#pp.xlim([0,3])

pp.subplot(212)
base='test_plot'
pp.title('Recurrence plot delta=')

markerline2, stemlines2, baseline2 = stem(x_filt_all_p*float(1)/float(w[0]), los_p_filt_all_p*float(1)/float(w[0]),'b',linefmt=" ",)
pp.matplotlib.markers.MarkerStyle('.')
setp(markerline2,'markerfacecolor','b',label='points')
pp.legend(fontsize= 'small')
pp.grid(True)
pp.xlabel('Time i [s]')
pp.ylabel('Time p [s]') 

#pp.xlim(0,3)
#pp.ylim(0,3)
pp.show()
#pp.savefig('plots/%s.jpg' %(str(base))
pp.close()  

但我不确定 100% 我的代码可以正常工作。有人可以看看我的代码,给我一些关于如何测试它的建议吗? 我不想使用 matlab 和 mathematica。这个想法是在 python 中创建一个独立的代码。 另外我还有另一个小问题,我无法更改绘图中的点大小。 最后,我已经尝试使用带有http://recurrence-plot.tk/online/index.php?state= 的交叉检查,但我无法使其工作。非常欢迎对我的代码或可能的交叉检查提出任何建议。 提前致谢

【问题讨论】:

    标签: python matplotlib time-series recurrence


    【解决方案1】:

    我知道这个问题已经很老了,但也许将来有人会偶然发现这个问题。

    既然你已经在使用 NumPy,让我推荐这个 sn-p:

    import numpy as np
    
    def rec_plot(s, eps=0.1, steps=10):
        N = s.size
        S = np.repeat(s[None,:], N, axis=0)
        Z = np.floor(np.abs(S-S.T)/eps)
        Z[Z>steps] = steps
    
        return Z
    

    它最初创建 (N, N) 大小的方形空数组。然后通过S-S.T 减去所有可能的点组合,这隐含地等价于矩阵减法,其中一个矩阵的所有行为 S,另一个矩阵的所有列为 S。

    除以eps 和 floor 是用于询问这些点之间有多少 eps 差异的简写。然后Z[Z&gt;steps] 是有界的,因此每当某物从该点超过steps 乘以eps 时,它就是最大值,并且将简单地以相同的值绘制。

    这个解决方案不是最理想的,因为它首先创建了两个 NxN 矩阵,这对于大 N 来说太多了。对于 N>10000,这绝对不好。由于您使用的是 SciPy,我们可以使用它的 distance 库。下面是更优化的实现:

    import numpy as np
    from scipy.spatial.distance import pdist, squareform
    
    def rec_plot(s, eps=0.1, steps=10):
        d = pdist(s[:,None])
        d = np.floor(d/eps)
        d[d>steps] = steps
        Z = squareform(d)
        return Z
    

    您可以找到https://laszukdawid.com/tag/recurrence-plot/https://github.com/laszukdawid/recurrence-plot 的使用示例。

    【讨论】:

    • 您为“更大”数据集建议的代码存在分段错误问题。 datascience.stackexchange.com/questions/18675/…
    • @drN 是的,代码对于大型数据集效率低下。尽管此代码运行良好,但您可能会在绘制结果时遇到一些问题。在您的示例中使用一些稀疏矩阵表示可能会更好。
    • 谢谢。有什么修改建议吗?最良好的祝愿。
    • 非常感谢您提供的代码!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2013-12-11
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多