Skip to content Skip to sidebar Skip to footer

Recurrence Plot In Python

I am trying to clusterize paterns in time series as I ask in How to clustering syllable types with python? I try using to solve my problem using the recurrence plots technique, so

Solution 1:

I understand this question is quite old, but maybe someone will stumble on this in future.

Since you are already using NumPy let me suggest this snippet:

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

It initially creates square empty array of (N, N) size. Then it subtract all possible combinations of points via S-S.T, which is implicitly equivalent to having matrix subtraction where one matrix has all rows S and the other all columns S.

Dividing by eps and flooring is for a short hand for asking of how many eps difference is between those points. Then Z[Z>steps] is bounding, so that whenever something is more than steps times eps from the point, then it's max and will be simply plot with same value.

This solution is suboptimal as it first creates two NxN matrices, which for large N is too much. For N>10000 this is definitely not good. Since you are using SciPy we can use its distance library. Below is more optimal implementation:

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

Examples of usage you can find https://laszukdawid.com/tag/recurrence-plot/ or https://github.com/laszukdawid/recurrence-plot.


Post a Comment for "Recurrence Plot In Python"