How to use the ruptures.base.BaseCost function in ruptures

To help you get started, we’ve selected a few ruptures examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github deepcharles / ruptures / ruptures / detection / window.py View on Github external
``'custom_cost'`` is not None.
            custom_cost (BaseCost, optional): custom cost function. Defaults to None.
            min_size (int, optional): minimum segment length.
            jump (int, optional): subsample (one every *jump* points).
            params (dict, optional): a dictionary of parameters for the cost instance.

        Returns:
            self
        """
        self.min_size = min_size
        self.jump = jump
        self.width = 2 * (width // 2)
        self.n_samples = None
        self.signal = None
        self.inds = None
        if custom_cost is not None and isinstance(custom_cost, BaseCost):
            self.cost = custom_cost
        else:
            if params is None:
                self.cost = cost_factory(model=model)
            else:
                self.cost = cost_factory(model=model, **params)
        self.score = list()
github deepcharles / ruptures / ruptures / costs / costrbf.py View on Github external
.. bibliography:: ../biblio.bib
    :style: alpha
    :cited:
    :labelprefix: KER
    :keyprefix: ker-


"""
import numpy as np
from scipy.spatial.distance import pdist, squareform

from ruptures.exceptions import NotEnoughPoints
from ruptures.base import BaseCost


class CostRbf(BaseCost):

    r"""
    Kernel cost function (rbf kernel).
    """

    model = "rbf"

    def __init__(self):
        self.gram = None
        self.min_size = 2

    def fit(self, signal):
        """Sets parameters of the instance.

        Args:
            signal (array): signal. Shape (n_samples,) or (n_samples, n_features)
github deepcharles / ruptures / ruptures / costs / pw_constant.py View on Github external
start (int): start of the segment
            end (int): end of the segment

        Returns:
            float: segment cost

        Raises:
            NotEnoughPoints: when the segment is too short (less than ``'min_size'`` samples).
        """
        if end - start < self.min_size:
            raise NotEnoughPoints

        return self.signal[start:end].var(axis=0).sum()


class Cost(BaseCost):

    """Compute error (in different norms) when approximating a signal with a constant value."""

    def __init__(self, model="constantl2"):
        assert model in [
            "constantl1", "constantl2", "rbf"], "Choose different model."
        self.model = model
        if self.model in ["constantl1", "constantl2", "rbf"]:
            self.min_size = 2

        self.signal = None
        self.gram = None

    def fit(self, signal):
        """Update the parameters of the instance to fit the signal.
github deepcharles / ruptures / ruptures / costs / costl1.py View on Github external
.. rubric:: References

.. bibliography:: ../biblio.bib
    :style: alpha
    :cited:
    :labelprefix: C1
    :keyprefix: c1-

"""
import numpy as np

from ruptures.base import BaseCost
from ruptures.costs import NotEnoughPoints


class CostL1(BaseCost):

    r"""
    Least absolute deviation.
    """

    model = "l1"

    def __init__(self):
        self.signal = None
        self.min_size = 2

    def fit(self, signal):
        """Set parameters of the instance.

        Args:
            signal (array): signal. Shape (n_samples,) or (n_samples, n_features)
github deepcharles / ruptures / ruptures / costs / pw_constant.py View on Github external
"""Cost functions for piecewise constant functions."""
import numpy as np
from scipy.spatial.distance import pdist, squareform
from ruptures.costs import NotEnoughPoints

from ruptures.base import BaseCost


class CostL2(BaseCost):

    r"""Computes the approximation error when the signal is assumed to be piecewise constant.
    Formally, for a signal :math:`\{y_t\}_t` on an interval :math:`I`,

    .. math:: c(y_{}) = \sum_{t\in I} \|y_t - \bar{y}\|^2_2

    where :math:`\bar{y}=\frac{1}{|I|} \sum\limits_{t\in I} y_t`.
    """

    def __init__(self):
        self.signal = None
        self.min_size = 2

    def fit(self, signal):
        """Sets parameters of the instance.
github deepcharles / ruptures / ruptures / costs / costrank.py View on Github external
.. bibliography:: ../biblio.bib
    :style: alpha
    :cited:
    :labelprefix: RA
    :keyprefix: rank-
"""
import numpy as np
from numpy.linalg import pinv, LinAlgError
from scipy.stats.mstats import rankdata

from ruptures.base import BaseCost
from ruptures.costs import NotEnoughPoints


class CostRank(BaseCost):
    r"""
    Rank-based cost function
    """

    model = "rank"

    def __init__(self):
        self.inv_cov = None
        self.ranks = None
        self.min_size = 2

    def fit(self, signal):
        """Set parameters of the instance.

        Args:
            signal (array): signal. Shape (n_samples,) or (n_samples, n_features)
github deepcharles / ruptures / ruptures / costs / costnormal.py View on Github external
Code explanation
----------------------------------------------------------------------------------------------------

.. autoclass:: ruptures.costs.CostNormal
    :members:
    :special-members: __init__

"""
import numpy as np
from numpy.linalg import slogdet

from ruptures.base import BaseCost
from ruptures.costs import NotEnoughPoints


class CostNormal(BaseCost):

    """Maximum Gaussian likelihood."""

    model = "normal"

    def __init__(self):
        self.signal = None
        self.min_size = 2

    def fit(self, signal):
        """Set parameters of the instance.

        Args:
            signal (array): signal. Shape (n_samples,) or (n_samples, n_features)

        Returns:
github deepcharles / ruptures / ruptures / costs / costl2.py View on Github external
Code explanation
----------------------------------------------------------------------------------------------------

.. autoclass:: ruptures.costs.CostL2
    :members:
    :special-members: __init__

"""
from ruptures.costs import NotEnoughPoints

from ruptures.base import BaseCost


class CostL2(BaseCost):

    r"""
    Least squared deviation.
    """

    model = "l2"

    def __init__(self):
        self.signal = None
        self.min_size = 2

    def fit(self, signal):
        """Set parameters of the instance.

        Args:
            signal (array): signal. Shape (n_samples,) or (n_samples, n_features)
github deepcharles / ruptures / ruptures / costs / costautoregressive.py View on Github external
.. bibliography:: ../biblio.bib
    :style: alpha
    :cited:
    :labelprefix: AR
    :keyprefix: ar-

"""
import numpy as np
from numpy.lib.stride_tricks import as_strided
from numpy.linalg import lstsq

from ruptures.base import BaseCost
from ruptures.costs import NotEnoughPoints


class CostAR(BaseCost):

    r"""
    Least-squares estimate for changes in autoregressive coefficients.
    """

    model = "ar"

    def __init__(self, order=4):
        self.signal = None
        self.covar = None
        self.min_size = max(5, order + 1)
        self.order = order

    def fit(self, signal):
        """Set parameters of the instance.
        The signal must be 1D.
github deepcharles / ruptures / ruptures / detection / dynp.py View on Github external
def __init__(self, model="l2", custom_cost=None, min_size=2, jump=5, params=None):
        """Creates a Dynp instance.

        Args:
            model (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if ``'custom_cost'`` is not None.
            custom_cost (BaseCost, optional): custom cost function. Defaults to None.
            min_size (int, optional): minimum segment length.
            jump (int, optional): subsample (one every *jump* points).
            params (dict, optional): a dictionary of parameters for the cost instance.

        Returns:
            self
        """
        self.seg = lru_cache(maxsize=None)(self._seg)  # dynamic programming
        if custom_cost is not None and isinstance(custom_cost, BaseCost):
            self.cost = custom_cost
        else:
            if params is None:
                self.cost = cost_factory(model=model)
            else:
                self.cost = cost_factory(model=model, **params)
        self.min_size = max(min_size, self.cost.min_size)
        self.jump = jump
        self.n_samples = None