Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert timeseries to image matrix

I have a numpy array X of timeserieses. Something like that:

[[0.05, -0.021, 0.003, 0.025, -0.001, -0.023, 0.095, 0.001, -0.018]
[0.015, 0.011, -0.032, -0.044, -0.002, 0.032, -0.051, -0.03, -0.020]
[0.04, 0.081, -0.02, 0.014, 0.063, -0.077, 0.059, 0.031, 0.025]]

I can plot this with

fig, axes = plt.subplots(3, 1)
for i in range(3):
    axes[i].plot(X[i])
plt.show()

Then something like the following appears (the plots do not show the demo values I wrote above but other values with similar structure). So each row in X is one timeseries. enter image description here

But I want to have a numpy array which describes each timeseries as a grayscale image (because I want to use it for a cnn later). So I think what I need should be something like that:

[[[0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 1]
[0, 0, 1, 0, 0, 0]]
[[0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0]]...]

How is it (if possible: efficiently) possible to convert each timeseries into a matrix, which describes the timeseries as an image. So each row in the old array (e.g. this:

[0.05, -0.021, 0.003, 0.025, -0.001, -0.023, 0.095, 0.001, -0.018])

should be converted to a 2D matrix (e.g. something like this:

[[0, 0, 0, 0, 0, 1] [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1] [0, 0, 1, 0, 0, 0]]

Alternative describtion: Every row in X describes one timeseries. For each row in X I need a 2D matrix describing the timeseries as an image (like the plot shown above)

"Solution": Seems there is no nice solution to do this. I used this workaround now:

fig = plt.figure()
fig.add_subplot(111)
fig.tight_layout(pad=0)
plt.axis('off')
plt.plot(X[0], linewidth=3)
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

The data contains the 2D matrix now and could be plotted with plt.imshow(data) again with some loss of quality.

like image 709
L3n95 Avatar asked May 25 '18 09:05

L3n95


1 Answers

Take a look at these kaggle challange. It think you also want to implement parts of this paper like they do.

Maybe you can also use the function that they adopted from another SO question:

#modified from https://stackoverflow.com/questions/33650371/recurrence-plot-in-python
def recurrence_plot(s, eps=None, steps=None):
    if eps==None: eps=0.1
    if steps==None: steps=10
    d = sk.metrics.pairwise.pairwise_distances(s)
    d = np.floor(d / eps)
    d[d > steps] = steps
    #Z = squareform(d)
    return d
like image 177
Fabian Avatar answered Oct 17 '22 19:10

Fabian