-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathfeature_transformation.py
99 lines (72 loc) · 2.24 KB
/
feature_transformation.py
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
29
30
31
32
33
34
35
36
37
38
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
"""
This example shows how you can search for useful feature
transformations for your dataset. This example is very similar to
"feature_selection". It adds the possibility to change the features
with the numpy functions in the search space.
"""
import numpy as np
import itertools
from sklearn.datasets import load_diabetes
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from hyperactive import Hyperactive
data = load_diabetes()
X, y = data.data, data.target
def get_feature_list(opt):
feature_list = []
for key in opt.keys():
if "feature" not in key:
continue
nth_feature = int(key.rsplit(".", 1)[1])
if opt[key] == 0:
continue
elif opt[key] == 1:
feature = X[:, nth_feature]
feature_list.append(feature)
else:
feature = opt[key](X[:, nth_feature])
feature_list.append(feature)
return feature_list
def model(opt):
feature_list = get_feature_list(opt)
X_new = np.array(feature_list).T
knr = KNeighborsRegressor(n_neighbors=opt["n_neighbors"])
scores = cross_val_score(knr, X_new, y, cv=5)
score = scores.mean()
return score
def log_f(*args, **kwargs):
return np.log(*args, **kwargs)
def square_f(*args, **kwargs):
return np.square(*args, **kwargs)
def sqrt_f(*args, **kwargs):
return np.sqrt(*args, **kwargs)
def sin_f(*args, **kwargs):
return np.sin(*args, **kwargs)
def cos_f(*args, **kwargs):
return np.cos(*args, **kwargs)
# features can be used (1), not used (0) or transformed for training
features_search_space = [
1,
0,
log_f,
square_f,
sqrt_f,
sin_f,
cos_f,
]
search_space = {
"n_neighbors": list(range(1, 100)),
"feature.0": features_search_space,
"feature.1": features_search_space,
"feature.2": features_search_space,
"feature.3": features_search_space,
"feature.4": features_search_space,
"feature.5": features_search_space,
"feature.6": features_search_space,
"feature.7": features_search_space,
"feature.8": features_search_space,
"feature.9": features_search_space,
}
hyper = Hyperactive()
hyper.add_search(model, search_space, n_iter=150)
hyper.run()