Add a custom algorithm
In order to integrate a custom algorithm in PHOTONAI, all you need to do is provide a class adhering to the popular
scikit-learn object API.
In the following we will demonstrate an example to integrate a custom transformer to the
Hyperpipe.
First, implement your data processing logic like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | # we use BaseEstimator as to prepare the transformer for hyperparameter optimization
# we inherit the get_params and set_params methods
from sklearn.base import BaseEstimator
class CustomTransformer(BaseEstimator):
def __init__(self, param1=0, param2=None):
# it is important that you name your params the same in the constructor
# stub as well as in your class variables!
self.param1 = param1
self.param2 = param2
def fit(self, data, targets=None, **kwargs):
"""
Adjust the underlying model or method to the data.
Returns
-------
IMPORTANT: must return self!
"""
return self
def transform(self, data, targets=None, **kwargs):
"""
Apply the method's logic to the data.
"""
return data
|
Afterwards, register your element with the photon registry like this.
Custom elements must only be registered once.
| from photonai.base import PhotonRegistry
custom_element_root_folder = "./"
registry = PhotonRegistry(custom_elements_folder=custom_element_root_folder)
registry.register(photon_name='MyCustomTransformer',
class_str='custom_transformer.CustomTransformer',
element_type='Transformer')
# show information about the element
registry.info("MyCustomTransformer")
|
Afterwards, you can use your custom element in the pipeline like this.
Importantly, the custom_elements_folder must be activated for each use as the folder's content, and therefore the
custom class implementation might otherwise not be accessible by the python script.
| from photonai.base import PhotonRegistry, Hyperpipe, PipelineElement
custom_element_root_folder = "./"
registry = PhotonRegistry(custom_elements_folder=custom_element_root_folder)
# This add the custom algorithm folder to the python path in order to import and instantiate the algorithm
registry.activate()
# then use it
my_pipe = Hyperpipe("...")
my_pipe += PipelineElement('MyCustomTransformer', hyperparameters={'param1': [1, 2, 3]})
|