eckity.sklearn_compatible.sklearn_wrapper

 1from sklearn.base import BaseEstimator
 2from sklearn.utils.validation import check_is_fitted, check_X_y
 3
 4
 5class SklearnWrapper(BaseEstimator):
 6    """
 7    Sklearn-compatible wrapper to support evolution using sklearn methods.
 8
 9    Parameters
10    ----------
11    algorithm: Algorithm
12        Wrapped Evolutionary algorithm.
13        The Wrapper invokes 'evolve' and 'execute' methods of the algorithm
14        during the fitting and prediction process, respectively.
15
16    Attributes
17    ----------
18    is_fitted: bool
19        Determines if the model is fitted (evolved).
20    """
21
22    def __init__(self,
23                 algorithm):
24        self.algorithm = algorithm
25
26    def fit(self, X, y=None):
27        """
28       Run evolutionary algorithm.
29       Use `fit` in a sklearn setting.
30        Parameters
31        ----------
32        X : {array-like, sparse matrix} of shape (n_samples, n_features)
33            The training input samples.
34        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
35            The target values (real numbers).
36        Returns
37        -------
38        self : SklearnWrapper
39            Fitted (evolved) model.
40        """
41        # Check that X and y have correct shape
42        X, y = check_X_y(X, y)
43
44        for sub_pop in self.algorithm.population.sub_populations:
45            sub_pop.evaluator.set_context((X, y))
46
47        self.algorithm.evolve()
48        self.is_fitted_ = True
49        return self
50
51    def predict(self, X):
52        """
53        Compute output using best evolved individual.
54        Use `predict` in a sklearn setting.
55        Input is a numpy array.
56
57        Parameters
58        ----------
59        X : array-like or sparse matrix of (num samples, num feautres)
60
61        Returns
62        -------
63        y : array, shape (num samples,)
64            Returns predicted values.
65
66        """
67
68        # Check is fit had been called
69        check_is_fitted(self)
70
71        return self.algorithm.best_of_run_.execute(X)
72
73    # def __sklearn_is_fitted__(self):
74    #     return self.is_fitted_
75
76    def get_params(self, deep=True):
77        return self.__getstate__()
78
79    def set_params(self, **parameters):
80        self.algorithm.__setstate__(parameters)
81        return self
82
83    def partial_fit(self, X, y, classes=None):
84        raise NotImplementedError('not implemented yet')
85        pass
86
87    def __getstate__(self):
88        state = self.__dict__.copy()
89        if 'is_fitted_' in state:
90            del state['is_fitted_']
91        return state
92
93    def __setstate__(self, state):
94        self.__dict__.update(state)
class SklearnWrapper(sklearn.base.BaseEstimator):
 6class SklearnWrapper(BaseEstimator):
 7    """
 8    Sklearn-compatible wrapper to support evolution using sklearn methods.
 9
10    Parameters
11    ----------
12    algorithm: Algorithm
13        Wrapped Evolutionary algorithm.
14        The Wrapper invokes 'evolve' and 'execute' methods of the algorithm
15        during the fitting and prediction process, respectively.
16
17    Attributes
18    ----------
19    is_fitted: bool
20        Determines if the model is fitted (evolved).
21    """
22
23    def __init__(self,
24                 algorithm):
25        self.algorithm = algorithm
26
27    def fit(self, X, y=None):
28        """
29       Run evolutionary algorithm.
30       Use `fit` in a sklearn setting.
31        Parameters
32        ----------
33        X : {array-like, sparse matrix} of shape (n_samples, n_features)
34            The training input samples.
35        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
36            The target values (real numbers).
37        Returns
38        -------
39        self : SklearnWrapper
40            Fitted (evolved) model.
41        """
42        # Check that X and y have correct shape
43        X, y = check_X_y(X, y)
44
45        for sub_pop in self.algorithm.population.sub_populations:
46            sub_pop.evaluator.set_context((X, y))
47
48        self.algorithm.evolve()
49        self.is_fitted_ = True
50        return self
51
52    def predict(self, X):
53        """
54        Compute output using best evolved individual.
55        Use `predict` in a sklearn setting.
56        Input is a numpy array.
57
58        Parameters
59        ----------
60        X : array-like or sparse matrix of (num samples, num feautres)
61
62        Returns
63        -------
64        y : array, shape (num samples,)
65            Returns predicted values.
66
67        """
68
69        # Check is fit had been called
70        check_is_fitted(self)
71
72        return self.algorithm.best_of_run_.execute(X)
73
74    # def __sklearn_is_fitted__(self):
75    #     return self.is_fitted_
76
77    def get_params(self, deep=True):
78        return self.__getstate__()
79
80    def set_params(self, **parameters):
81        self.algorithm.__setstate__(parameters)
82        return self
83
84    def partial_fit(self, X, y, classes=None):
85        raise NotImplementedError('not implemented yet')
86        pass
87
88    def __getstate__(self):
89        state = self.__dict__.copy()
90        if 'is_fitted_' in state:
91            del state['is_fitted_']
92        return state
93
94    def __setstate__(self, state):
95        self.__dict__.update(state)

Sklearn-compatible wrapper to support evolution using sklearn methods.

Parameters
  • algorithm (Algorithm): Wrapped Evolutionary algorithm. The Wrapper invokes 'evolve' and 'execute' methods of the algorithm during the fitting and prediction process, respectively.
Attributes
  • is_fitted (bool): Determines if the model is fitted (evolved).
SklearnWrapper(algorithm)
23    def __init__(self,
24                 algorithm):
25        self.algorithm = algorithm
algorithm
def fit(self, X, y=None):
27    def fit(self, X, y=None):
28        """
29       Run evolutionary algorithm.
30       Use `fit` in a sklearn setting.
31        Parameters
32        ----------
33        X : {array-like, sparse matrix} of shape (n_samples, n_features)
34            The training input samples.
35        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
36            The target values (real numbers).
37        Returns
38        -------
39        self : SklearnWrapper
40            Fitted (evolved) model.
41        """
42        # Check that X and y have correct shape
43        X, y = check_X_y(X, y)
44
45        for sub_pop in self.algorithm.population.sub_populations:
46            sub_pop.evaluator.set_context((X, y))
47
48        self.algorithm.evolve()
49        self.is_fitted_ = True
50        return self

Run evolutionary algorithm. Use fit in a sklearn setting. Parameters


X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (real numbers). Returns


self : SklearnWrapper Fitted (evolved) model.

def predict(self, X):
52    def predict(self, X):
53        """
54        Compute output using best evolved individual.
55        Use `predict` in a sklearn setting.
56        Input is a numpy array.
57
58        Parameters
59        ----------
60        X : array-like or sparse matrix of (num samples, num feautres)
61
62        Returns
63        -------
64        y : array, shape (num samples,)
65            Returns predicted values.
66
67        """
68
69        # Check is fit had been called
70        check_is_fitted(self)
71
72        return self.algorithm.best_of_run_.execute(X)

Compute output using best evolved individual. Use predict in a sklearn setting. Input is a numpy array.

Parameters
  • X (array-like or sparse matrix of (num samples, num feautres)):
Returns
  • y (array, shape (num samples,)): Returns predicted values.
def get_params(self, deep=True):
77    def get_params(self, deep=True):
78        return self.__getstate__()

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.
def set_params(self, **parameters):
80    def set_params(self, **parameters):
81        self.algorithm.__setstate__(parameters)
82        return self

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as ~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.
def partial_fit(self, X, y, classes=None):
84    def partial_fit(self, X, y, classes=None):
85        raise NotImplementedError('not implemented yet')
86        pass
def set_partial_fit_request(unknown):

Descriptor for defining set_{method}_request methods in estimators.

New in version 1.3.

Parameters
  • name (str): The name of the method for which the request function should be created, e.g. "fit" would create a set_fit_request function.
  • keys (list of str): A list of strings which are accepted parameters by the created function, e.g. ["sample_weight"] if the corresponding method accepts it as a metadata.
  • validate_keys (bool, default=True): Whether to check if the requested parameters fit the actual parameters of the method.
Notes

This class is a descriptor 1 and uses PEP-362 to set the signature of the returned function 2.

References