1+ """
2+ ====================================================================
3+ Extending Auto-Sklearn with Classification Component
4+ ====================================================================
5+
6+ The following example demonstrates how to create a new classification
7+ component for using in auto-sklearn.
8+ """
9+
10+ from ConfigSpace .configuration_space import ConfigurationSpace
11+ from ConfigSpace .hyperparameters import CategoricalHyperparameter , \
12+ UniformIntegerHyperparameter , UniformFloatHyperparameter
13+
14+ import sklearn .metrics
15+ import autosklearn .classification
16+ import autosklearn .pipeline .components .classification
17+ from autosklearn .pipeline .components .base \
18+ import AutoSklearnClassificationAlgorithm
19+ from autosklearn .pipeline .constants import DENSE , SIGNED_DATA , UNSIGNED_DATA , \
20+ PREDICTIONS
21+
22+
23+ # Create MLP classifier component for auto-sklearn.
24+ class MLPClassifier (AutoSklearnClassificationAlgorithm ):
25+ def __init__ (self ,
26+ hidden_layer_depth ,
27+ num_nodes_per_layer ,
28+ activation ,
29+ alpha ,
30+ solver ,
31+ random_state = None ,
32+ ):
33+ self .hidden_layer_depth = hidden_layer_depth
34+ self .num_nodes_per_layer = num_nodes_per_layer
35+ self .activation = activation
36+ self .alpha = alpha
37+ self .solver = solver
38+ self .random_state = random_state
39+
40+ def fit (self , X , y ):
41+ self .num_nodes_per_layer = int (self .num_nodes_per_layer )
42+ self .hidden_layer_depth = int (self .hidden_layer_depth )
43+ self .alpha = float (self .alpha )
44+
45+ from sklearn .neural_network import MLPClassifier
46+ hidden_layer_sizes = tuple (self .num_nodes_per_layer \
47+ for i in range (self .hidden_layer_depth ))
48+
49+ self .estimator = MLPClassifier (hidden_layer_sizes = hidden_layer_sizes ,
50+ activation = self .activation ,
51+ alpha = self .alpha ,
52+ solver = self .solver ,
53+ random_state = self .random_state ,
54+ )
55+ self .estimator .fit (X , y )
56+ return self
57+
58+ def predict (self , X ):
59+ if self .estimator is None :
60+ raise NotImplementedError ()
61+ return self .estimator .predict (X )
62+
63+ def predict_proba (self , X ):
64+ if self .estimator is None :
65+ raise NotImplementedError ()
66+ return self .estimator .predict_proba (X )
67+
68+ @staticmethod
69+ def get_properties (dataset_properties = None ):
70+ return {'shortname' :'MLP Classifier' ,
71+ 'name' : 'MLP CLassifier' ,
72+ 'handles_regression' : False ,
73+ 'handles_classification' : True ,
74+ 'handles_multiclass' : True ,
75+ 'handles_multilabel' : False ,
76+ 'is_deterministic' : False ,
77+ # Both input and output must be tuple(iterable)
78+ 'input' : [DENSE , SIGNED_DATA , UNSIGNED_DATA ],
79+ 'output' : [PREDICTIONS ]
80+ }
81+
82+ @staticmethod
83+ def get_hyperparameter_search_space (dataset_properties = None ):
84+ cs = ConfigurationSpace ()
85+ hidden_layer_depth = UniformIntegerHyperparameter (
86+ name = "hidden_layer_depth" , lower = 1 , upper = 3 , default_value = 1
87+ )
88+ num_nodes_per_layer = UniformIntegerHyperparameter (
89+ name = "num_nodes_per_layer" , lower = 16 , upper = 216 , default_value = 32
90+ )
91+ activation = CategoricalHyperparameter (
92+ name = "activation" , choices = ['identity' , 'logistic' , 'tanh' , 'relu' ],
93+ default_value = 'relu'
94+ )
95+ alpha = UniformFloatHyperparameter (
96+ name = "alpha" , lower = 0.0001 , upper = 1.0 , default_value = 0.0001
97+ )
98+ solver = CategoricalHyperparameter (
99+ name = "solver" , choices = ['lbfgs' , 'sgd' , 'adam' ], default_value = 'adam'
100+ )
101+ cs .add_hyperparameters ([hidden_layer_depth ,
102+ num_nodes_per_layer ,
103+ activation ,
104+ alpha ,
105+ solver ,
106+ ])
107+ return cs
108+
109+
110+ # Add MLP classifier component to auto-sklearn.
111+ autosklearn .pipeline .components .classification .add_classifier (MLPClassifier )
112+ cs = MLPClassifier .get_hyperparameter_search_space ()
113+ print (cs )
114+
115+ # Generate data.
116+ from sklearn .datasets import load_breast_cancer
117+ from sklearn .model_selection import train_test_split
118+ X , y = load_breast_cancer (return_X_y = True )
119+ X_train , X_test , y_train , y_test = train_test_split (X , y )
120+
121+ # Fit MLP classifier to the data.
122+ clf = autosklearn .classification .AutoSklearnClassifier (
123+ time_left_for_this_task = 20 ,
124+ per_run_time_limit = 10 ,
125+ include_estimators = ['MLPClassifier' ],
126+ )
127+ clf .fit (X_train , y_train )
128+
129+ # Print test accuracy and statistics.
130+ y_pred = clf .predict (X_test )
131+ print ("accuracy: " , sklearn .metrics .accuracy_score (y_pred , y_test ))
132+ print (clf .sprint_statistics ())
133+ print (clf .show_models ())
0 commit comments