l1 trend filtering#

l1 trend filtering (Kim, Koh, Boyd & Gorinevsky, 2009).

Description#

On every channel, the detector estimates the piecewise-linear trend that minimises the penalised objective of Kim, Koh, Boyd and Gorinevsky (2009, eq. 5),

\[\min_x \; \frac12\|y-x\|_2^2 + \lambda\|D x\|_1,\]

where \(D\) is the second-order difference matrix. The kinks of the estimate (its nonzero second differences) are reported as change points: a piecewise-linear trend has an exact zero second difference between two kinks, so the detector is naturally aimed at changes of slope (trend breaks).

The problem is convex but not smooth; it is solved through its dual, the box-constrained QP of the paper (section 5.2, eq. 13),

\[\min_\nu \; \tfrac12\nu^\top D D^\top \nu - \nu^\top D y \quad \text{s.t. } |\nu| \le \lambda,\]

by OSQP followed by an exact active-set polish: the free block of the dual system is solved in closed form once the saturated coordinates are identified, which certifies the KKT conditions of the unique optimum. The values of interest of penalty depend on the scale of the series; above \(\lambda_{max} = \|(D D^\top)^{-1} D y\|_\infty\) (paper, eq. 7, exposed as lambda_max_) the estimate is the best affine fit and no change point is reported.

Multivariate series use the “sum of l1 norms” extension of the paper (section 7.5): each channel is filtered separately with the same penalty and the change points are the union of the channel kinks. The group-penalty variant of the same section (common kinks across channels, sum of l2 norms) requires a conic solver and is not implemented.

Type: change point detection
Supervision: unsupervised
Scope: univariate and multivariate
Complexity: \(O(n)\) memory per solve; the OSQP iterations are \(O(n)\) each, and the polish is a sparse solve of the reduced system
Requires: OSQP (pip install tsseg[l1tf])

Parameters#

Name

Type

Default

Description

penalty

float

1.0

l1 penalty \(\lambda > 0\) on the second differences of the trend; compare with lambda_max_.

knot_tol

float

1e-3

Tolerance of the kink tests (dual saturation |dual| >= (1 - knot_tol) * penalty and relative second difference).

eps_abs

float

1e-6

Absolute tolerance of OSQP (steers the active-set search only; the polish certifies the solution).

eps_rel

float

1e-6

Relative tolerance of OSQP.

max_iter

int

200000

Maximum number of OSQP iterations.

polish

bool

True

Whether OSQP polishes its solution.

axis

int

0

Time axis.

Attributes#

change_points_

Sorted indices of the kinks of the estimated trends.

trend_

The estimated piecewise-linear trends, same shape as the input.

second_diff_

The second differences of the estimated trends (exact zeros between kinks).

lambda_max_

\(\|(D D^\top)^{-1} D y\|_\infty\) over channels: above this penalty the estimate is the best affine fit (paper, eq. 7).

Usage#

import numpy as np
from tsseg.algorithms import TrendFilteringDetector

t = np.arange(500)
x = 2.0 + 0.01 * t + 0.05 * np.maximum(t - 250, 0) + 0.1 * np.sin(t)
detector = TrendFilteringDetector(penalty=5.0)
change_points = detector.fit_predict(x)

Implementation: original reimplementation. The convex problem is solved by OSQP (Apache-2.0); its model setup follows the dual formulation of the paper’s section 5.2 without reusing any code of the authors’ MATLAB implementation (GPL-2, interfaces CVX). The solver differs from the paper’s specialized interior-point method (its section 6), but the problem is strictly convex, so the minimiser is the same, and the KKT solution is certified by the active-set polish.

Reference: Kim, S.-J., Koh, K., Boyd, S. and Gorinevsky, D. (2009), l1 Trend Filtering, SIAM Review 51(2):339-360.

Validation#

The implementation reproduces the properties of the paper on its own grounds: the objective values and trends match an independent CVXPY/Clarabel solve of eq. (5) to 1e-8 (relative) on synthetic and real series, the kinks carry the same second differences as the reference solve, \(\|y - x\|_\infty \le 4\lambda\) holds (property 6), the estimate is the best affine fit above \(\lambda_{max}\) (eq. 7), and the estimate is equivariant when the data and the penalty are scaled together. On the S&P 500 log-price series of the paper’s figure 2 (n=2000) the detected kink positions agree with an independent solve of the same problem; the paper reports 8 change points at \(\lambda = 100\) where the exact KKT support has 12 (including kinks with a second difference a hundred times smaller than the largest one, which the paper’s figure does not separate).

API reference#

l1 trend filtering change point detector (Kim, Koh, Boyd & Gorinevsky, 2009).

The detector minimises the penalised objective of the paper (eq. 5) on every channel,

minimize (1/2)||y - x||^2 + lambda ||D x||_1,

with D the second-order difference matrix, and reports the kinks (changes of slope) of the estimated piecewise-linear trend as change points. The convex problem is solved exactly on its dual (the box-constrained QP of the paper’s section 5.2) by OSQP with polishing, which recovers the exact KKT solution of the identified active set. For multivariate series the penalty is the sum of the per-channel l1 norms (paper section 7.5); the channels are then estimated separately and the change points are the union of the channel kinks.

class TrendFilteringDetector(*, penalty=1.0, knot_tol=0.001, eps_abs=1e-06, eps_rel=1e-06, max_iter=200000, polish=True, axis=0)[source]#

Bases: BaseSegmenter

l1 trend filtering change point detector.

Estimates, on every channel, the piecewise-linear trend that minimises the penalised objective of Kim, Koh, Boyd and Gorinevsky (2009, eq. 5),

\[\min_x \; \frac12\|y-x\|_2^2 + \lambda\|D x\|_1,\]

where \(D\) is the second-order difference matrix. The kinks of the estimate (its nonzero second differences) are reported as change points: a piecewise-linear trend has an exact zero second difference between two kinks. The problem is convex but not smooth; it is solved through its dual, the box-constrained QP (paper, section 5.2, eq. 13),

\[\min_\nu \; \tfrac12\nu^\top D D^\top \nu - \nu^\top D y \quad \text{s.t. } |\nu| \le \lambda,\]

by OSQP with polishing (the KKT system of the identified active set is then solved exactly). The milder penalty, the more change points; above \(\lambda_{max} = \|(D D^\top)^{-1} D y\|_\infty\) (paper, eq. 7, exposed as the attribute lambda_max_) the trend estimate is the best affine fit and no change point is reported.

Multivariate series use the “sum of l1 norms” extension of the paper (section 7.5): each channel is filtered separately with the same penalty, and the change points are the union of the channel kinks. The group-penalty variant of section 7.5 (common kinks across channels, sum of l2 norms) requires a conic solver and is not implemented.

Parameters:
  • penalty (float) – Smoothing parameter \(\lambda > 0\): the l1 penalty on the second differences of the trend. The values of interest depend on the scale of the series (compare with the attribute lambda_max_).

  • knot_tol (float) – A coordinate counts as a kink (change point) when its dual is saturated, |dual| >= (1 - knot_tol) * penalty, and its second difference exceeds knot_tol times the largest second difference. The solver accuracy must be significantly tighter than knot_tol.

  • eps_abs (float) – Absolute and relative tolerances of OSQP. They only steer the identification of the active set: the active-set polish then certifies the solution, so they can stay well above the kink tolerance; refining them past 1e-6 multiplies the iterations of the ADMM without changing the certified answer.

  • eps_rel (float) – Absolute and relative tolerances of OSQP. They only steer the identification of the active set: the active-set polish then certifies the solution, so they can stay well above the kink tolerance; refining them past 1e-6 multiplies the iterations of the ADMM without changing the certified answer.

  • max_iter (int) – Maximum number of OSQP iterations.

  • polish (bool) – Whether OSQP polishes its solution (solves the KKT system of the identified active set exactly). Keep it on: the polish is what makes the exact zeros of the second differences reliable.

  • axis (int) – Axis of X that represents time.

change_points_#

Sorted indices (one per channel union) where a new segment starts, the kinks of the estimated trends.

Type:

np.ndarray

trend_#

The estimated piecewise-linear trends, same shape as the input.

Type:

np.ndarray

second_diff_#

The second differences of the estimated trends (exact zeros between kinks).

Type:

np.ndarray

lambda_max_#

\(\|(D D^\top)^{-1} D y\|_\infty\) (norm over channels): above this penalty the estimate would be the best affine fit.

Type:

float

Notes

The solver differs from the paper’s specialized interior-point method (its section 6): same strictly convex problem, so the minimiser is the same; OSQP returns it up to its tolerances, and the polished second differences are exact zeros between kinks. The lambda_max_ formula is the paper’s eq. 7; the fitting bound ||y - x||_inf <= 4 lambda is its property (6).

References

Examples

>>> import numpy as np
>>> from tsseg.algorithms.l1tf.detector import TrendFilteringDetector
>>> t = np.arange(500)
>>> x = 2.0 + 0.01 * t + 0.05 * np.maximum(t - 250, 0) + 0.1 * np.sin(t)
>>> detector = TrendFilteringDetector(penalty=5.0)
>>> detector.fit(x)
TrendFilteringDetector(penalty=5.0)
>>> detector.predict(x)
array([250])
set_fit_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

axis (Union[bool, None, str]) – Metadata routing for axis parameter in fit.

Returns:

self – The updated object.

Return type:

TrendFilteringDetector

set_predict_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the predict method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

axis (Union[bool, None, str]) – Metadata routing for axis parameter in predict.

Returns:

self – The updated object.

Return type:

TrendFilteringDetector