Skip to content

Module fri.model.base_initmodel

Base class for our initial baseline models which are used in Gridsearch. They store the constant parameters needed in the model and the dynamic instance attributes when fitted.

View Source
"""

    Base class for our initial baseline models which are used in Gridsearch.

    They store the constant parameters needed in the model

        and the dynamic instance attributes when fitted.

"""

from abc import ABC, abstractmethod

from sklearn.base import BaseEstimator

class InitModel(ABC, BaseEstimator):

    HYPERPARAMETER = {}

    SOLVER_PARAMS = {"solver": "ECOS"}

    def __init__(self, **parameters):

        self.model_state = {}

        self.constraints = {}

    @abstractmethod

    def fit(self, X, y, **kwargs):

        pass

    @abstractmethod

    def predict(self, X):

        pass

    @abstractmethod

    def score(self, X, y, **kwargs):

        pass

    def make_scorer(self):

        return None, None

    @property

    def L1_factor(self):

        try:

            return self.constraints["w_l1"]

        except:

            raise NotImplementedError(

                "Baseline model does not provide (L1) normalization constant. Expected l1 norm of model weights (e.g. w)."

            )

class LUPI_InitModel(InitModel):

    @property

    def L1_factor_priv(self):

        try:

            return self.constraints["w_priv_l1"]

        except:

            raise NotImplementedError(

                "Baseline model does not provide LUPI (L1) normalization constant. Expected l1 norm of LUPI model weights (e.g. w_priv)."

            )

Classes

InitModel

class InitModel(
    **parameters
)

Helper class that provides a standard way to create an ABC using inheritance.

View Source
class InitModel(ABC, BaseEstimator):

    HYPERPARAMETER = {}

    SOLVER_PARAMS = {"solver": "ECOS"}

    def __init__(self, **parameters):

        self.model_state = {}

        self.constraints = {}

    @abstractmethod

    def fit(self, X, y, **kwargs):

        pass

    @abstractmethod

    def predict(self, X):

        pass

    @abstractmethod

    def score(self, X, y, **kwargs):

        pass

    def make_scorer(self):

        return None, None

    @property

    def L1_factor(self):

        try:

            return self.constraints["w_l1"]

        except:

            raise NotImplementedError(

                "Baseline model does not provide (L1) normalization constant. Expected l1 norm of model weights (e.g. w)."

            )

Ancestors (in MRO)

  • abc.ABC
  • sklearn.base.BaseEstimator

Descendants

  • fri.model.base_initmodel.LUPI_InitModel
  • fri.model.classification.Classification_SVM
  • fri.model.lupi_classification.LUPI_Classification_SVM
  • fri.model.ordinal_regression.OrdinalRegression_SVM
  • fri.model.regression.Regression_SVR

Class variables

HYPERPARAMETER
SOLVER_PARAMS

Instance variables

L1_factor

Methods

fit
def fit(
    self,
    X,
    y,
    **kwargs
)
View Source
    @abstractmethod

    def fit(self, X, y, **kwargs):

        pass
get_params
def get_params(
    self,
    deep=True
)

Get parameters for this estimator.

Parameters

deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params : dict Parameter names mapped to their values.

View Source
    def get_params(self, deep=True):

        """

        Get parameters for this estimator.

        Parameters

        ----------

        deep : bool, default=True

            If True, will return the parameters for this estimator and

            contained subobjects that are estimators.

        Returns

        -------

        params : dict

            Parameter names mapped to their values.

        """

        out = dict()

        for key in self._get_param_names():

            value = getattr(self, key)

            if deep and hasattr(value, 'get_params'):

                deep_items = value.get_params().items()

                out.update((key + '__' + k, val) for k, val in deep_items)

            out[key] = value

        return out
make_scorer
def make_scorer(
    self
)
View Source
    def make_scorer(self):

        return None, None
predict
def predict(
    self,
    X
)
View Source
    @abstractmethod

    def predict(self, X):

        pass
score
def score(
    self,
    X,
    y,
    **kwargs
)
View Source
    @abstractmethod

    def score(self, X, y, **kwargs):

        pass
set_params
def set_params(
    self,
    **params
)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as :class:~sklearn.pipeline.Pipeline). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Parameters

**params : dict Estimator parameters.

Returns

self : estimator instance Estimator instance.

View Source
    def set_params(self, **params):

        """

        Set the parameters of this estimator.

        The method works on simple estimators as well as on nested objects

        (such as :class:`~sklearn.pipeline.Pipeline`). The latter have

        parameters of the form ``<component>__<parameter>`` so that it's

        possible to update each component of a nested object.

        Parameters

        ----------

        **params : dict

            Estimator parameters.

        Returns

        -------

        self : estimator instance

            Estimator instance.

        """

        if not params:

            # Simple optimization to gain speed (inspect is slow)

            return self

        valid_params = self.get_params(deep=True)

        nested_params = defaultdict(dict)  # grouped by prefix

        for key, value in params.items():

            key, delim, sub_key = key.partition('__')

            if key not in valid_params:

                raise ValueError('Invalid parameter %s for estimator %s. '

                                 'Check the list of available parameters '

                                 'with `estimator.get_params().keys()`.' %

                                 (key, self))

            if delim:

                nested_params[key][sub_key] = value

            else:

                setattr(self, key, value)

                valid_params[key] = value

        for key, sub_params in nested_params.items():

            valid_params[key].set_params(**sub_params)

        return self

LUPI_InitModel

class LUPI_InitModel(
    **parameters
)

Helper class that provides a standard way to create an ABC using inheritance.

View Source
class LUPI_InitModel(InitModel):

    @property

    def L1_factor_priv(self):

        try:

            return self.constraints["w_priv_l1"]

        except:

            raise NotImplementedError(

                "Baseline model does not provide LUPI (L1) normalization constant. Expected l1 norm of LUPI model weights (e.g. w_priv)."

            )

Ancestors (in MRO)

  • fri.model.base_initmodel.InitModel
  • abc.ABC
  • sklearn.base.BaseEstimator

Descendants

  • fri.model.lupi_ordinal_regression.LUPI_OrdinalRegression_SVM
  • fri.model.lupi_regression.LUPI_Regression_SVM

Class variables

HYPERPARAMETER
SOLVER_PARAMS

Instance variables

L1_factor
L1_factor_priv

Methods

fit
def fit(
    self,
    X,
    y,
    **kwargs
)
View Source
    @abstractmethod

    def fit(self, X, y, **kwargs):

        pass
get_params
def get_params(
    self,
    deep=True
)

Get parameters for this estimator.

Parameters

deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params : dict Parameter names mapped to their values.

View Source
    def get_params(self, deep=True):

        """

        Get parameters for this estimator.

        Parameters

        ----------

        deep : bool, default=True

            If True, will return the parameters for this estimator and

            contained subobjects that are estimators.

        Returns

        -------

        params : dict

            Parameter names mapped to their values.

        """

        out = dict()

        for key in self._get_param_names():

            value = getattr(self, key)

            if deep and hasattr(value, 'get_params'):

                deep_items = value.get_params().items()

                out.update((key + '__' + k, val) for k, val in deep_items)

            out[key] = value

        return out
make_scorer
def make_scorer(
    self
)
View Source
    def make_scorer(self):

        return None, None
predict
def predict(
    self,
    X
)
View Source
    @abstractmethod

    def predict(self, X):

        pass
score
def score(
    self,
    X,
    y,
    **kwargs
)
View Source
    @abstractmethod

    def score(self, X, y, **kwargs):

        pass
set_params
def set_params(
    self,
    **params
)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as :class:~sklearn.pipeline.Pipeline). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Parameters

**params : dict Estimator parameters.

Returns

self : estimator instance Estimator instance.

View Source
    def set_params(self, **params):

        """

        Set the parameters of this estimator.

        The method works on simple estimators as well as on nested objects

        (such as :class:`~sklearn.pipeline.Pipeline`). The latter have

        parameters of the form ``<component>__<parameter>`` so that it's

        possible to update each component of a nested object.

        Parameters

        ----------

        **params : dict

            Estimator parameters.

        Returns

        -------

        self : estimator instance

            Estimator instance.

        """

        if not params:

            # Simple optimization to gain speed (inspect is slow)

            return self

        valid_params = self.get_params(deep=True)

        nested_params = defaultdict(dict)  # grouped by prefix

        for key, value in params.items():

            key, delim, sub_key = key.partition('__')

            if key not in valid_params:

                raise ValueError('Invalid parameter %s for estimator %s. '

                                 'Check the list of available parameters '

                                 'with `estimator.get_params().keys()`.' %

                                 (key, self))

            if delim:

                nested_params[key][sub_key] = value

            else:

                setattr(self, key, value)

                valid_params[key] = value

        for key, sub_params in nested_params.items():

            valid_params[key].set_params(**sub_params)

        return self