|
1
|
|
|
""" |
|
2
|
|
|
This example shows how you can search for useful feature |
|
3
|
|
|
transformations for your dataset. This example is very similar to |
|
4
|
|
|
"feature_selection". It adds the possibility to change the features |
|
5
|
|
|
with the numpy functions in the search space. |
|
6
|
|
|
|
|
7
|
|
|
""" |
|
8
|
|
|
|
|
9
|
|
|
import numpy as np |
|
10
|
|
|
import itertools |
|
11
|
|
|
from sklearn.datasets import load_boston |
|
12
|
|
|
from sklearn.model_selection import cross_val_score |
|
13
|
|
|
from sklearn.neighbors import KNeighborsRegressor |
|
14
|
|
|
from hyperactive import Hyperactive |
|
15
|
|
|
|
|
16
|
|
|
data = load_boston() |
|
17
|
|
|
X, y = data.data, data.target |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
def get_feature_list(opt): |
|
21
|
|
|
feature_list = [] |
|
22
|
|
|
for key in opt.keys(): |
|
23
|
|
|
if "feature" not in key: |
|
24
|
|
|
continue |
|
25
|
|
|
|
|
26
|
|
|
nth_feature = int(key.rsplit(".", 1)[1]) |
|
27
|
|
|
|
|
28
|
|
|
if opt[key] is False: |
|
29
|
|
|
continue |
|
30
|
|
|
elif opt[key] is True: |
|
31
|
|
|
feature = X[:, nth_feature] |
|
32
|
|
|
feature_list.append(feature) |
|
33
|
|
|
else: |
|
34
|
|
|
feature = opt[key](X[:, nth_feature]) |
|
35
|
|
|
feature_list.append(feature) |
|
36
|
|
|
|
|
37
|
|
|
return feature_list |
|
38
|
|
|
|
|
39
|
|
|
|
|
40
|
|
|
def model(opt): |
|
41
|
|
|
feature_list = get_feature_list(opt) |
|
42
|
|
|
X_new = np.array(feature_list).T |
|
43
|
|
|
|
|
44
|
|
|
knr = KNeighborsRegressor(n_neighbors=opt["n_neighbors"]) |
|
45
|
|
|
scores = cross_val_score(knr, X_new, y, cv=5) |
|
46
|
|
|
score = scores.mean() |
|
47
|
|
|
|
|
48
|
|
|
return score |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
# features can be used (True), not used (False) or transformed for training |
|
52
|
|
|
features_search_space = [ |
|
53
|
|
|
True, |
|
54
|
|
|
False, |
|
55
|
|
|
np.log, |
|
56
|
|
|
np.square, |
|
57
|
|
|
np.sqrt, |
|
58
|
|
|
np.sin, |
|
59
|
|
|
np.cos, |
|
60
|
|
|
] |
|
61
|
|
|
|
|
62
|
|
|
search_space = { |
|
63
|
|
|
"n_neighbors": list(range(1, 100)), |
|
64
|
|
|
"feature.0": features_search_space, |
|
65
|
|
|
"feature.1": features_search_space, |
|
66
|
|
|
"feature.2": features_search_space, |
|
67
|
|
|
"feature.3": features_search_space, |
|
68
|
|
|
"feature.4": features_search_space, |
|
69
|
|
|
"feature.5": features_search_space, |
|
70
|
|
|
"feature.6": features_search_space, |
|
71
|
|
|
"feature.7": features_search_space, |
|
72
|
|
|
"feature.8": features_search_space, |
|
73
|
|
|
"feature.9": features_search_space, |
|
74
|
|
|
"feature.10": features_search_space, |
|
75
|
|
|
"feature.11": features_search_space, |
|
76
|
|
|
"feature.12": features_search_space, |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
|
|
80
|
|
|
hyper = Hyperactive() |
|
81
|
|
|
hyper.add_search(model, search_space, n_iter=150) |
|
82
|
|
|
hyper.run() |
|
83
|
|
|
|