Repository navigation
[ENH] Implement PELTSegmenter for optimal time series changepoint detection - #3969
shivamkumxr wants to merge 23 commits into
Conversation
Thank you for contributing to
|
baraline
left a comment
There was a problem hiding this comment.
Not a correctness review, only looked at testing side, some functions to move.
There was a problem hiding this comment.
thanks for this, I am not that familiar with the algorithm and dont have the time to become so, so went for an AI review below. This is from gemini carbon, next one I will put claude on.
I did a full algorithmic, performance, and test review and found a few substantive issues that need addressing before this can be merged:
1. Premature pruning under min_size >= 2 breaks global optimality (aeon/segmentation/_pelt.py, lines 176-185)
The docstring states that PELTSegmenter guarantees the globally optimal solution under the chosen cost and penalty. However, at step t, line 180 immediately discards candidate tau whenever F[tau] + seg_costs[tau] > F[t].
In Killick et al. (2012, Theorem 3.1), pruning tau via F[t] relies on replacing a partition (..., tau, s) with (..., t, s) at future steps s > t. When min_size >= 2, (t, s] is only a valid segment once s >= t + min_size. For intermediate steps s in {t + 1, ..., t + min_size - 1}, t is inadmissible as a changepoint whereas tau is still admissible, so deleting tau immediately at t can prune the true global optimum.
Minimal counterexample (cost="l2", penalty=5.0, min_size=2, jump=1):
X = np.array([3.0, 9.0, 0.0, 2.0, 10.0])
PELTSegmenter(cost="l2", penalty=5.0, min_size=2).fit_predict(X)
# Returns array([2]) with penalised cost 18.0 + 56.0 + 5.0 = 79.0,
# whereas array([]) (no changepoint) has strictly lower cost 78.8!Here tau = 0 is pruned at t = 4 (F[4] = 25.0 < -5.0 + 49.0 = 44.0), and then at t = 5, t = 4 cannot be used because 5 - 4 < min_size.
Suggested fix: When np.isfinite(F[t]) and F[tau] + seg_costs[tau] >= F[t], schedule tau to expire at t + min_size (e.g. expire[tau] = min(expire[tau], t + min_size)) rather than removing it before t can form a valid segment. Also avoid adding unreachable interior grid points 0 < t < min_size (where F[t] = np.inf) to candidates.
2. Scale sensitivity of "bic" / "aic" under cost="l2" and 1e-8 under cost="normal" (aeon/segmentation/_pelt.py, lines 254-285)
-
cost="l2"with"bic"/"aic":_cost_l2computes unnormalised RSS$\sum (y_t - \bar{y})^2$ , which scales by$\alpha^2$ ifXis multiplied by$\alpha$ , while_compute_penaltyreturnsp * log(n_timepoints)("bic") or2 * p("aic"), implicitly assuming unit noise variance$\sigma^2 = 1$ . Because$-2 \log L = \text{RSS} / \sigma^2 + \text{const}$ , rescalingmake_example_mean_shift_series(random_state=42)gives:-
0.01 * series->0changepoints -
1.0 * series->2changepoints ([100, 200]) -
10.0 * series->101changepoints -
100.0 * series->131changepoints
For automatic
"bic"/"aic"penalties under"l2", the penalty needs to account for noise variance (for example using a robust per-channel first-difference scale estimate such as MAD of$\Delta X_c / \sqrt{2}$ , with a fallback when$\Delta X_c$ has zero median absolute deviation on noiseless step series). Also please check the parameter countpper additional changepoint against Killick et al. (2012, Section 2.1), where each changepoint adds the segment parameters plus1for the changepoint location (d + 1/2 * d + 1), and make sure the formula and docstring match your intended definition. -
-
cost="normal":_cost_normaladds a fixed absolute1e-8insidenp.log(var + 1e-8). On low-amplitude signals (e.g.1e-5 * series, wherevar ~ 1e-10),1e-8dominatesvarandPELTSegmenter(cost="normal", penalty="bic", min_size=10)fails to detect any changepoints. Scaling epsilon relative to each channel's overall variance (falling back to1e-8only when a channel has zero variance) makes"normal"scale-invariant.
3. Performance: use Numba @njit for the inner DP loop (aeon/segmentation/_pelt.py, lines 149-186)
Running the dynamic programming loop in pure Python over set/dict containers and calling a Python staticmethod + NumPy slice reductions for every (t, tau) pair creates very high per-iteration overhead. In addition, line 180 uses <= (F[tau] + seg_costs[tau] <= F[t]), which keeps ties: on a constant series np.ones(n), 0.0 <= 0.0 holds for every tau > 0, so no candidate is ever pruned.
Locally, PELTSegmenter().fit_predict(np.ones(2500)) takes ~63 seconds (and stationary Gaussian n = 2500 takes ~10.5 seconds). numba is a core dependency in aeon; moving the DP loop into a @njit(cache=True) helper over flat float64/int64 arrays (with delayed >= tie-pruning) brings n = 2500 down to < 1 ms on constant input and ~6 ms on stationary Gaussian noise. Please also ensure tests pass with NUMBA_DISABLE_JIT=1 (pytest --nonumba) so the JIT body is covered.
4. Parameter and input validation edge cases (aeon/segmentation/_pelt.py, lines 130-140, 286-325)
- In Python,
isinstance(True, int)isTrue, whereasisinstance(np.int64(3), int)isFalse:penalty=True,penalty=False, andjump=Truesilently pass validation instead of raisingValueError.min_size=np.int64(3)andjump=np.int64(2)raiseValueError, which breaks NumPy integer values from hyperparameter grids. Please accept(int, np.integer)(ornumbers.Integral) while explicitly rejectingbool.
penalty=np.nanandpenalty=np.infpassself.penalty < 0(False) and silently return[]; please checknp.isfinite(self.penalty).- Input
Xcontainingnp.infor-np.infpassesBaseSeriesEstimator._check_X(which checksisnan), emits aRuntimeWarningindata - data.mean(...), and silently returns[]; please raise aValueErrorwhen non-finite values are present inX.
5. Data generation exports (aeon/testing/data_generation/_series.py, __init__.py)
Moving the synthetic shift generators into aeon.testing.data_generation makes sense, but right now this adds 6 public functions to aeon.testing.data_generation:
- Please drop the 3 duplicate aliases (
make_mean_shift_series,make_variance_shift_series,make_multivariate_series). make_example_multivariate_seriesis too generic a name alongsidemake_example_2d_numpy_seriesgiven that it specifically generates a 2-segment mean shift. Consider consolidating all three into a single segmentation helper (e.g.make_example_segment_seriessupportingn_channels, mean/variance shifts,axis, and optionally returning the true changepoint indices), and match_series.py'srandom_statehandling (np.random.RandomStateorcheck_random_state) for consistency with the rest of the module.
6. Tests (aeon/segmentation/tests/test_pelt.py, aeon/testing/data_generation/tests/test_series.py)
- Avoid magic numbers:
test_pelt.pycallsmake_example_mean_shift_series(random_state=42)using hidden defaults and then hard-codes100and200in assertions;test_series.pysimilarly hard-codes30,20, and3instead of definingn_timepoints/n_channelsvariables once and reusing them. Intest_series.py, please also assert that the generated segments actually exhibit the requested mean/variance shift rather than checking shape alone. - Prune / tighten redundant checks:
test_pelt_get_paramsis already covered bycheck_estimatorand can be removed;test_pelt_aic_penaltyshould verify exact equivalence against the manual AIC penalty formula rather thanlen(cps) >= 2; the invalid-parameter tests can be combined with@pytest.mark.parametrize. - Add exact-optimality &
axis=0tests: Please add a test comparingPELTSegmenteragainst an unpruned / brute-force partition search on small 1D and 2D series (covering both"l2"and"normal",min_size >= 2,jump >= 1,axis=0andaxis=1, and the[3.0, 9.0, 0.0, 2.0, 10.0]case above) to verify the global optimality guarantee directly.
|
this should be fixed with #4029, merging to test |
…xr/aeon into feature/pelt-segmenter
|
Thanks @TonyBagnall and @baraline for the detailed reviews and feedback! All requested changes and edge cases have been resolved, verified locally, and committed: 1. Pruning under
|
TonyBagnall
left a comment
There was a problem hiding this comment.
Thanks for the substantial revision.
One remaining question concerns the BIC/AIC parameter counts. The implementation uses p=2d for both L2 and Gaussian costs, where d is the number of channels. However, changepoint locations are shared across channels. I would expect d+1 parameters for L2 and 2d+1 for Gaussian if counting the changepoint location as a parameter, as discussed in my original review.
Could you check this against the reference and either correct the formulas or explain the alternative convention being used? Please include a multivariate test of the resulting penalty calculation.
Otherwise this looks close to approval.
|
Thanks @TonyBagnall, you're right, and thanks for pointing me back to the reference. The changepoint location is shared across channels, so it should count once, not once per channel. Following Killick et al. (2012, Sec 2.1), I've switched to For L2 the penalty stays in RSS units, so it is The docstring now states this convention. I also added All tests pass locally, with and without Numba ( |
…xr/aeon into feature/pelt-segmenter
Reference Issues/PRs
Closes #3948
What does this implement/fix? Explain your changes.
Adds
PELTSegmenterunderaeon.segmentationbased on Killick et al. (2012).Summary of changes:
PELTSegmenteron top ofBaseSegmenter.'bic'/'aic'.test_pelt.pyand patched_yield_segmentation_checks.pyto handle empty changepoint edge cases during generic estimator checks.Does your contribution introduce a new dependency? If yes, which one?
No.
PR checklist
PELTSegmenterto API documentation (docs/api_reference/segmentation.rst).test_pelt.py) and docstrings followingnumpydocstandards.check_estimator(PELTSegmenter).