tslearn icon indicating copy to clipboard operation
tslearn copied to clipboard

MatrixProfile (numpy implementation) returns all NaN for a NaN-padded / variable length time series

Open SajalDevX opened this issue 1 month ago • 0 comments

Describe the bug MatrixProfile declares allow_nan and allow_variable_length, but with the default implementation="numpy" any time series that contains a NaN gets a profile that is NaN everywhere. In a variable length dataset built with to_time_series_dataset, that means every series shorter than the longest one comes out as all NaN, even the positions whose subsequences have no padding in them.

implementation="stump" handles the same input fine: it returns the correct profile for the valid subsequences and inf for the ones that overlap the padding.

The cause is in MatrixProfile._transform: the pairwise distances are computed with pdist, so every distance to a subsequence that contains a NaN is NaN, and dists.min(axis=1) then propagates that NaN to every row.

To Reproduce

from tslearn.matrix_profile import MatrixProfile
from tslearn.utils import to_time_series_dataset

a = [0., 1., 3., 2., 9., 1., 14., 15., 1., 2., 2., 10., 7.]
b = a + [3., 5., 8.]
X = to_time_series_dataset([a, b])

print(MatrixProfile(subsequence_length=4).fit_transform([a])[0, :, 0])
# [0.642 0.286 1.64  0.898 1.28  1.782 2.987 2.839 0.286 0.642]

print(MatrixProfile(subsequence_length=4).fit_transform(X)[0, :, 0])
# [nan nan nan nan nan nan nan nan nan nan nan nan nan]

print(MatrixProfile(subsequence_length=4, implementation="stump").fit_transform(X)[0, :, 0])
# [0.642 0.286 1.64  0.898 1.28  1.782 2.987 2.839 0.286 0.642 inf inf inf]

(values rounded) The same happens with scale=False, and with a NaN in the middle of a single series: the numpy implementation gives all NaN while stump only puts inf on the subsequences that overlap the NaN.

Expected behavior The numpy implementation should agree with stump: subsequences containing a NaN should not poison the profile of the others, so the profile of a padded series matches the profile of the unpadded series on its valid positions.

Environment (please complete the following information):

  • OS: Linux
  • tslearn version: main (0.10.0.dev, a7df17b), numpy 2.4.6, scipy 1.17.1, stumpy 1.14.1

Additional context A one-line fix is to give NaN distances an infinite value, the same way the exclusion band is handled, right before taking the minimum. I'd be happy to open a PR with that and a regression test.

SajalDevX avatar Oct 05 '26 12:10 SajalDevX