Skip to content

SwitchCase

Implements a SwitchCase or fork transformer.

This class makes it easy to design, in a modular way, complex pipelines, with both discrete choices and continuous hyperparameters for hyperparameter tuning.

The SwitchCase can handle estimators implementing predict, transformers implementing transform and imblearn resamplers implementing fit_resample.

It's also possible to include sklearn Pipelines inside the cases. However, imblearn Pipelines should be included with extra care, as their internal design does not allow them to be nested. See examples for worked out examples and explanation of this restriction.

SwitchCase

Bases: _BaseComposition

Selectively applies result of one transformer object depending on switch.

Parameters:

Name Type Description Default
cases list of tuples (str, transformer)

Transformer objects to be applied to the data, conditioned on the value of the next parameter (switch). The first half of each tuple is the name of the transformer, and it has two functions: to determine (along with the switch) what is the transformer that will be applied and to specify the parameters of the transformer using double underscore. If transformer == "passthrough", it will apply the identity function. Transformers can be:

  • Sklearn transformers implementing at least fit and transform.
  • Sklearn estimators implementing at least fit and predict.
  • Imblearn resamplers implementing at least fit_resample.
required
switch str

It determines the transformer to be applied to the data.

required
Source code in nestedcvtraining/switch_case.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
class SwitchCase(_BaseComposition):
    """Selectively applies result of one transformer object depending on switch.
    Args:
        cases (list of tuples (str, transformer) ): Transformer objects to be applied
            to the data, conditioned on the value of the next parameter (switch). The first half of
            each tuple is the name of the transformer, and it has two functions:
            to determine (along with the switch) what is the transformer that will be applied
            and to specify the parameters of the transformer using double underscore.
            If transformer == "passthrough", it will apply the identity function.
            Transformers can be:

            - Sklearn transformers implementing at least `fit` and `transform`.
            - Sklearn estimators implementing at least `fit` and `predict`.
            - Imblearn resamplers implementing at least `fit_resample`.
        switch (str): It determines the transformer to be applied to the data.
    """

    _required_parameters = ["cases", "switch"]

    def __init__(
        self, cases, switch
    ):
        self.cases = cases
        self.switch = switch
        self._validate_switch()
        self._validate_transformers()

    @property
    def cases_names(self):
        return [name for name, _ in self.cases]

    @property
    def current_transformer(self):
        for name, trans in self.cases:
            if trans == "passthrough":
                trans = FunctionTransformer()
            if name == self.switch:
                return trans

    @property
    def current_transformer_idx(self):
        idx = 0
        for name, trans in self.cases:
            if name == self.switch:
                return idx
            idx += 1

    def _validate_switch(self):
        if self.switch not in self.cases_names:
            raise AttributeError(f"Value of switch {self.switch} is not among cases names {self.cases_names}")

    def _validate_transformers(self):
        names, transformers = zip(*self.cases)

        self._validate_names(names)

        for t in transformers:
            if t == "passthrough":
                continue
            if not (
                hasattr(t, "fit") or hasattr(t, "fit_transform") or hasattr(t, "fit_resample")
            ):
                raise TypeError(
                    "All transformers should implement fit or fit_transform or "
                    "fit_resample (but not both) or be a string 'passthrough' "
                    "'%s' (type %s) doesn't)" % (t, type(t))
                )

    def get_params(self, deep=True):
        """Get parameters for this estimator.
        Returns the parameters given in the constructor as well as the
        estimators contained within the `cases` of the
        `SwitchCase`.
        Args:
            deep (bool): If True, will return the parameters for this estimator and
                contained subobjects that are estimators.
        Returns:
            params (dict): mapping of string to any
                Parameter names mapped to their values.
        """
        return self._get_params("cases", deep=deep)

    def set_params(self, **kwargs):
        """Set the parameters of this estimator.
        Valid parameter keys can be listed with ``get_params()``. Note that
        you can directly set the parameters of the estimators contained in
        `cases`.
        Args:
            **kwargs (dict): Parameters of this estimator or parameters of estimators contained
                in `cases`. Parameters of the transformers may be set
                using its name and the parameter name separated by a '__'.
        Returns:
            self (object): SwitchCase class instance.
        """
        self._set_params("cases", **kwargs)
        self._validate_switch()
        self._validate_transformers()
        return self

    def get_feature_names_out(self, input_features=None):
        """Get output feature names for transformation.
        Args:
            input_features (array-like of str or None): Input features.
        Returns:
            feature_names_out (ndarray of str): Transformed feature names.
        """
        transformer = self.current_transformer
        name = self.cases[self.current_transformer_idx][0]
        feature_names = []
        feature_names.extend(
            [f"{name}__{f}" for f in transformer.get_feature_names_out(input_features)]
        )
        return np.asarray(feature_names, dtype=object)

    @available_if(_current_transformer_has("fit"))
    def fit(self, X, y=None, **fit_params):
        idx = self.current_transformer_idx
        transformer = self.current_transformer
        transformer.fit(X, y, **fit_params)
        self.cases[idx] = (self.cases[idx][0], transformer)
        return self

    @available_if(_current_transformer_has("fit_transform"))
    def fit_transform(self, X, y=None, **fit_params):
        transformer = self.current_transformer
        idx = self.current_transformer_idx
        Xt = transformer.fit_transform(X, y, **fit_params)
        self.cases[idx] = (self.cases[idx][0], transformer)
        return Xt

    @available_if(_current_transformer_has("fit_resample"))
    def fit_resample(self, X, y=None, **fit_params):
        transformer = self.current_transformer
        idx = self.current_transformer_idx
        X_res, y_res = transformer.fit_resample(X, y, **fit_params)
        self.cases[idx] = (self.cases[idx][0], transformer)
        return X_res, y_res

    @available_if(_current_transformer_has("transform"))
    def transform(self, X):
        transformer = self.current_transformer
        return transformer.transform(X)

    @available_if(_current_transformer_has("predict"))
    def predict(self, X):
        transformer = self.current_transformer
        return transformer.predict(X)

    @available_if(_current_transformer_has("fit_predict"))
    def fit_predict(self, X, y=None, **fit_params):
        transformer = self.current_transformer
        idx = self.current_transformer_idx
        y_pred = transformer.fit_predict(X, y, **fit_params)
        self.cases[idx] = (self.cases[idx][0], transformer)
        return y_pred

    @available_if(_current_transformer_has("predict_proba"))
    def predict_proba(self, X):
        transformer = self.current_transformer
        return transformer.predict_proba(X)

    @available_if(_current_transformer_has("decision_function"))
    def decision_function(self, X):
        transformer = self.current_transformer
        return transformer.decision_function(X)

    @available_if(_current_transformer_has("score_samples"))
    def score_samples(self, X):
        transformer = self.current_transformer
        return transformer.score_samples(X)

    @available_if(_current_transformer_has("predict_log_proba"))
    def predict_log_proba(self, X):
        transformer = self.current_transformer
        return transformer.predict_log_proba(X)

    @available_if(_current_transformer_has("inverse_transform"))
    def inverse_transform(self, Xt):
        transformer = self.current_transformer
        return transformer.inverse_transform(Xt)

    @available_if(_current_transformer_has("score"))
    def score(self, X, y=None, sample_weight=None):
        transformer = self.current_transformer
        score_params = {}
        if sample_weight is not None:
            score_params["sample_weight"] = sample_weight
        return transformer.score(X, y, **score_params)

    @property
    def n_features_in_(self):
        transformer = self.current_transformer
        return transformer.n_features_in_

    @property
    def feature_names_in(self):
        transformer = self.current_transformer
        return transformer.feature_names_in_

    @property
    def classes_(self):
        transformer = self.current_transformer
        return transformer.classes_

    def __sklearn_is_fitted__(self):
        transformer = self.current_transformer
        check_is_fitted(transformer)
        return True

    def _sk_visual_block_(self):
        names, transformers = zip(*self.cases)
        return _VisualBlock("parallel", transformers, names=names)

get_feature_names_out

get_feature_names_out(input_features=None)

Get output feature names for transformation.

Parameters:

Name Type Description Default
input_features array-like of str or None

Input features.

None

Returns:

Name Type Description
feature_names_out ndarray of str

Transformed feature names.

Source code in nestedcvtraining/switch_case.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def get_feature_names_out(self, input_features=None):
    """Get output feature names for transformation.
    Args:
        input_features (array-like of str or None): Input features.
    Returns:
        feature_names_out (ndarray of str): Transformed feature names.
    """
    transformer = self.current_transformer
    name = self.cases[self.current_transformer_idx][0]
    feature_names = []
    feature_names.extend(
        [f"{name}__{f}" for f in transformer.get_feature_names_out(input_features)]
    )
    return np.asarray(feature_names, dtype=object)

get_params

get_params(deep=True)

Get parameters for this estimator. Returns the parameters given in the constructor as well as the estimators contained within the cases of the SwitchCase.

Parameters:

Name Type Description Default
deep bool

If True, will return the parameters for this estimator and contained subobjects that are estimators.

True

Returns:

Name Type Description
params dict

mapping of string to any Parameter names mapped to their values.

Source code in nestedcvtraining/switch_case.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def get_params(self, deep=True):
    """Get parameters for this estimator.
    Returns the parameters given in the constructor as well as the
    estimators contained within the `cases` of the
    `SwitchCase`.
    Args:
        deep (bool): If True, will return the parameters for this estimator and
            contained subobjects that are estimators.
    Returns:
        params (dict): mapping of string to any
            Parameter names mapped to their values.
    """
    return self._get_params("cases", deep=deep)

set_params

set_params(**kwargs)

Set the parameters of this estimator. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in cases.

Parameters:

Name Type Description Default
**kwargs dict

Parameters of this estimator or parameters of estimators contained in cases. Parameters of the transformers may be set using its name and the parameter name separated by a '__'.

{}

Returns:

Name Type Description
self object

SwitchCase class instance.

Source code in nestedcvtraining/switch_case.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def set_params(self, **kwargs):
    """Set the parameters of this estimator.
    Valid parameter keys can be listed with ``get_params()``. Note that
    you can directly set the parameters of the estimators contained in
    `cases`.
    Args:
        **kwargs (dict): Parameters of this estimator or parameters of estimators contained
            in `cases`. Parameters of the transformers may be set
            using its name and the parameter name separated by a '__'.
    Returns:
        self (object): SwitchCase class instance.
    """
    self._set_params("cases", **kwargs)
    self._validate_switch()
    self._validate_transformers()
    return self