-
Notifications
You must be signed in to change notification settings - Fork 23
/
feature_selection_with_gbdt_and_optuna.py
149 lines (119 loc) · 4.67 KB
/
feature_selection_with_gbdt_and_optuna.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""
This example uses UCI ML California Housing dataset, which is a
regression dataset including 20k samples.
Dua, D. and Graff, C. (2019). UCI Machine Learning Repository
[http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of
Information and Computer Science.
"""
from functools import partial
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import lightgbm as lgb
import optuna
from xfeat import ArithmeticCombinations, Pipeline
from xfeat import GBDTFeatureExplorer
def main():
data = fetch_california_housing()
df = pd.DataFrame(
data=data.data,
columns=data.feature_names)
print("Before adding interaction features:")
evaluate_dataframe(df, data.target)
print("After adding interaction features:")
df = feature_engineering(df)
evaluate_dataframe(df, data.target)
print("After applying GBDTFeatureSelector:")
df = feature_selection(df, data.target)
evaluate_dataframe(df, data.target)
def feature_engineering(df):
cols = df.columns.tolist()
encoder = Pipeline([
ArithmeticCombinations(input_cols=cols,
drop_origin=False,
operator="+",
r=2,
output_suffix="_plus"),
ArithmeticCombinations(input_cols=cols,
drop_origin=False,
operator="*",
r=2,
output_suffix="_mul"),
ArithmeticCombinations(input_cols=cols,
drop_origin=False,
operator="-",
r=2,
output_suffix="_minus"),
ArithmeticCombinations(input_cols=cols,
drop_origin=False,
operator="+",
r=3,
output_suffix="_plus"),
])
return encoder.fit_transform(df)
def objective(df, selector, trial):
selector.set_trial(trial)
selector.fit(df)
input_cols = selector.get_selected_cols()
params = {
"objective": "regression",
"metric": "rmse",
"learning_rate": 0.1,
"verbosity": -1,
}
# Evaluate with selected columns
train_set = lgb.Dataset(df[input_cols], label=df["target"])
scores = lgb.cv(params, train_set, num_boost_round=100, stratified=False, seed=1)
rmsle_score = scores["rmse-mean"][-1]
return rmsle_score
def feature_selection(df, y):
input_cols = df.columns.tolist()
n_before_selection = len(input_cols)
df["target"] = np.log1p(y)
df_train, _ = train_test_split(df, test_size=0.5, random_state=1)
params = {
"objective": "regression",
"metric": "rmse",
"learning_rate": 0.1,
"verbosity": -1,
}
fit_params = {
"num_boost_round": 100,
}
selector = GBDTFeatureExplorer(input_cols=input_cols,
target_col="target",
fit_once=True,
threshold_range=(0.6, 1.0),
lgbm_params=params,
lgbm_fit_kwargs=fit_params)
study = optuna.create_study(direction="minimize")
study.optimize(partial(objective, df_train, selector), n_trials=20)
selector.from_trial(study.best_trial)
selected_cols = selector.get_selected_cols()
print(f" - {n_before_selection - len(selected_cols)} features are removed.")
return df[selected_cols]
def evaluate_dataframe(df, y):
X_train, X_test, y_train, y_test = train_test_split(df.values, y,
test_size=0.5,
random_state=1)
y_train = np.log1p(y_train)
params = {
"objective": "regression",
"metric": "rmse",
"learning_rate": 0.1,
"verbosity": -1,
}
train_set = lgb.Dataset(X_train, label=y_train)
scores = lgb.cv(params, train_set, num_boost_round=100, stratified=False, seed=1)
rmsle_score = scores["rmse-mean"][-1]
print(f" - CV RMSEL: {rmsle_score:.6f}")
booster = lgb.train(params, train_set, num_boost_round=100)
y_pred = booster.predict(X_test)
test_rmsle_score = rmse(np.log1p(y_test), y_pred)
print(f" - test RMSEL: {test_rmsle_score:.6f}")
def rmse(y_true, y_pred):
return np.sqrt(mean_squared_error(y_true, y_pred))
if __name__ == "__main__":
main()