Skip to content

Documentation for Switch

This class encapsulates several PipelineElements that belong at the same step of the pipeline, competing for being the best choice.

If for example you want to find out if Preprocessing A or Preprocessing B is better at this position in the pipe. Or you want to test if a random forest outperforms the good old SVM.

ATTENTION: This class is a construct that may be convenient but is not suitable for any complex optimizations. Currently optimization works for grid_search, random search and smac and the specializes switch optimizer.

Examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from photonai.base import PipelineElement, Switch
from photonai.optimization import IntegerRange
# Estimator Switch
svm = PipelineElement('SVC',
                      hyperparameters={'kernel': ['rbf', 'linear']})

tree = PipelineElement('DecisionTreeClassifier',
                       hyperparameters={'min_samples_split': IntegerRange(2, 5),
                                        'min_samples_leaf': IntegerRange(1, 5),
                                        'criterion': ['gini', 'entropy']})

my_pipe += Switch('EstimatorSwitch', [svm, tree])

__iadd__(self, pipeline_element) special

Add a new estimator or transformer object to the switch container. All items change their positions during testing.

Parameters:

Name Type Description Default
pipeline_element PipelineElement

Item that should be tested against other competing elements at that position in the pipeline.

required
Source code in photonai/base/photon_elements.py
def __iadd__(self, pipeline_element: PipelineElement):
    """
    Add a new estimator or transformer object to the switch container.
    All items change their positions during testing.

    Parameters:
        pipeline_element:
            Item that should be tested against other
            competing elements at that position in the pipeline.

    """
    super(Switch, self).__iadd__(pipeline_element)
    self.elements_dict[pipeline_element.name] = pipeline_element
    self.generate_private_config_grid()
    return self

__init__(self, name, elements=None, estimator_name='') special

Creates a new Switch object and generated the hyperparameter combination grid.

Parameters:

Name Type Description Default
name str

How the element is called in the pipeline.

required
elements List[photonai.base.photon_elements.PipelineElement]

The competing pipeline elements.

None
estimator_name str

-

''
Source code in photonai/base/photon_elements.py
def __init__(self, name: str, elements: List[PipelineElement] = None, estimator_name: str = ''):
    """
    Creates a new Switch object and generated the hyperparameter combination grid.

    Parameters:
        name:
            How the element is called in the pipeline.

        elements:
            The competing pipeline elements.

        estimator_name:
            -

    """
    self._name = name
    self.initial_name = self._name
    self.sklearn_name = self.name + "__current_element"
    self._hyperparameters = {}
    self._current_element = (1, 1)
    self.pipeline_element_configurations = []
    self.base_element = None
    self.disabled = False
    self.test_disabled = False
    self.batch_size = 0
    self.estimator_name = estimator_name

    self.needs_y = True
    self.needs_covariates = True
    # we assume we test models against each other, but only guessing
    self.is_estimator = True
    self.is_transformer = True
    self.identifier = "SWITCH:"
    self._random_state = False

    self.elements_dict = {}

    if elements:
        self.elements = elements
        self.generate_private_config_grid()
        for p_element in elements:
            self.elements_dict[p_element.name] = p_element
    else:
        self.elements = []

add(self, pipeline_element)

Add a new estimator or transformer object to the switch container. All items change their positions during testing.

Parameters:

Name Type Description Default
pipeline_element PipelineElement

Item that should be tested against other competing elements at that position in the pipeline.

required
Source code in photonai/base/photon_elements.py
def add(self, pipeline_element: PipelineElement):
    """
    Add a new estimator or transformer object to the switch container.
    All items change their positions during testing.

    Parameters:
        pipeline_element:
            Item that should be tested against other
            competing elements at that position in the pipeline.

    """
    self.__iadd__(pipeline_element)

predict_proba(self, X, **kwargs)

Predict probabilities. Base element needs predict_proba() function, otherwise return None.

Parameters:

Name Type Description Default
X ndarray

The array-like data with shape=[N, D], where N is the number of samples and D is the number of features.

required
**kwargs

Keyword arguments, not in use yet.

{}

Returns:

Type Description
Optional[numpy.ndarray]

Probabilities.

Source code in photonai/base/photon_elements.py
def predict_proba(self, X: np.ndarray, **kwargs) -> Union[np.ndarray, None]:
    """
    Predict probabilities. Base element needs predict_proba()
    function, otherwise return None.

    Parameters:
        X:
            The array-like data with shape=[N, D], where N is the number
            of samples and D is the number of features.

        **kwargs:
            Keyword arguments, not in use yet.

    Returns:
        Probabilities.

    """
    if not self.disabled:
        if hasattr(self.base_element.base_element, 'predict_proba'):
            return self.base_element.predict_proba(X)
        else:
            return None
    return X