-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgbm_2.py
227 lines (173 loc) · 9.78 KB
/
gbm_2.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import kaggle
import pandas as pd
import os
import lightgbm as lgbm
import optuna as opt
import seaborn as sns
import numpy as np
import gc
import shap
from scipy.stats import binom_test
from sklearn.model_selection import train_test_split
os.chdir("/Users/matthewlafferty/Dropbox/Kaggle/Tabular_Feb_2021/tabular-playground-series-feb-2021")
data = pd.read_csv('train.csv')
#!##########################################################################################################
#!##########################################################################################################
#! Functions
#!##########################################################################################################
def categorical_convert(X:pd.Series) -> pd.Series:
temp = X.astype('category').cat.codes
temp += 1
return temp
def create_shadow_feature(X:pd.Series) -> np.array:
temp = X.to_numpy(copy=True)
np.random.shuffle(temp)
return temp
#!##########################################################################################################
#!##########################################################################################################
#! Fixed parameters
#!##########################################################################################################
NUM_ITER = 3
TARGET = 'target'
NUM_BOOST_ROUNDS = 10000
NUM_FOLDS = 5
features = [x for x in list(data) if ('cat' in x) | ('cont' in x)]
cat_features = [x for x in list(data) if ('cat' in x)]
starting_params = {'boosting_type': 'gbdt',
'learning_rate': 0.25,
'metric':'rmse',
'objective':'regression'}
#!##########################################################################################################
#!##########################################################################################################
#! Converting categorical features
#!##########################################################################################################
cat_dict = {}
for f in cat_features:
for idx, c in enumerate(data[f].unique()):
cat_dict[(f,c)] = int(idx+1)
for f in cat_features:
for c in data[f].unique():
data[f] = np.where(data[f] == c, cat_dict[(f,c)], data[f])
data[f] = data[f].astype('int')
#!##########################################################################################################
#!##########################################################################################################
#! Feature Selection
#!##########################################################################################################
# shadow_features = features + [f + '_shadow' for f in features]
# shadow_cat_features = cat_features + [x + '_shadow' for x in cat_features]
# shap_values_results_df = pd.DataFrame(columns = shadow_features + [TARGET])
# data_shadow = data.copy()
# for i in range(NUM_ITER):
# # We will determine optimal parameters on a random sample. We'll use these parameters to construct a new model for each iteration.
# # Determining the hyperparameters takes time, so we'll do it once, and use these parameters to construct our models.
# for f in features:
# data_shadow[f + '_shadow'] = create_shadow_feature(data_shadow[f])
# data_train, data_temp = train_test_split(data_shadow, train_size=0.6, shuffle=True)
# dtrain = lgbm.Dataset(data=data_train[shadow_features],
# label=data_train[TARGET],
# feature_name=shadow_features,
# categorical_feature=shadow_cat_features)
# model = opt.integration.lightgbm.LightGBMTunerCV(params = starting_params,
# train_set = dtrain,
# num_boost_round = NUM_BOOST_ROUNDS,
# nfold = NUM_FOLDS,
# stratified=False,
# shuffle = True,
# feature_name=shadow_features,
# categorical_feature=shadow_cat_features,
# early_stopping_rounds=0.05*NUM_BOOST_ROUNDS,
# verbose_eval = 100,
# seed = 51)
# model.run()
# print(model.best_score)
# shadow_best_params = model.best_params
# data_val, data_test = train_test_split(data_temp, train_size=0.6, shuffle=True)
# del(data_temp)
# dval= lgbm.Dataset(data=data_val[shadow_features],
# label=data_val[TARGET],
# feature_name=shadow_features,
# categorical_feature=shadow_cat_features)
# shadow_model = lgbm.train(params=shadow_best_params,
# train_set=dtrain,
# num_boost_round=NUM_BOOST_ROUNDS,
# valid_sets=[dval],
# feature_name=shadow_features,
# categorical_feature=shadow_cat_features,
# early_stopping_rounds=0.05*NUM_BOOST_ROUNDS,
# verbose_eval=100)
# shadow_model.params["objective"] = "regression"
# shap_values = shap.TreeExplainer(shadow_model).shap_values(data_test[shadow_features])
# shap_values_df = pd.DataFrame(data = shap_values, columns = shadow_features)
# shap_values_results_df = pd.concat([shap_values_results_df, shap_values_df], axis = 0)
# cols_to_keep = []
# n = shap_values_results_df.shape[0]
# for col in features:
# x = np.sum(np.where(shap_values_results_df[col] < shap_values_results_df[col + '_shadow'], 1, 0))
# p_val = binom_test(x=x, n=n, p=0.5, alternative='greater')
# if p_val <= 0.05:
# cols_to_keep += [col]
# print(model.best_score) 0.8455077135158744
# cols_to_keep = ['cat1', 'cat2', 'cat4', 'cat6', 'cat7', 'cont0', 'cont1', 'cont3', 'cont4', 'cont5', 'cont7', 'cont8', 'cont9', 'cont10', 'cont11', 'cont12']
#!################################################################################################################################
#!################################################################################################################################
#! Determing optimal parameters for model with selected features.
dtrain = lgbm.Dataset(data=data[features],
label=data[TARGET],
feature_name=features,
categorical_feature=cat_features)
model = opt.integration.lightgbm.LightGBMTunerCV(params = starting_params,
train_set = dtrain,
num_boost_round = NUM_BOOST_ROUNDS,
nfold = NUM_FOLDS,
stratified=False,
shuffle = True,
feature_name=features,
categorical_feature=cat_features,
early_stopping_rounds=0.05*NUM_BOOST_ROUNDS,
verbose_eval = 100,
seed = 51)
model.run()
print(model.best_score)
all_features_params = model.best_params
all_features_params['learning_rate'] = 0.01
best_iter_list = []
for i in range(5):
X_train, X_val = train_test_split(data, train_size = 0.7, shuffle = True)
dtrain = lgbm.Dataset(data = X_train[features],
label = X_train[TARGET],
feature_name = features,
categorical_feature = cat_features)
dval = lgbm.Dataset(data = X_val[features],
label = X_val[TARGET],
feature_name = features,
categorical_feature = cat_features)
current_model = lgbm.train(params=all_features_params,
train_set=dtrain,
num_boost_round=250000,
valid_sets=[dval],
feature_name=features,
categorical_feature=cat_features,
early_stopping_rounds=1000,
verbose_eval=100)
best_iter_current = current_model.best_iteration
best_iter_list += [best_iter_current]
print(current_model.best_score)
#!#############################################################################
#! FINAL MODEL
dtrain = lgbm.Dataset(data = data[features],
label = data[TARGET],
feature_name = features,
categorical_feature = cat_features)
final_model = lgbm.train(params=all_features_params,
train_set=dtrain,
num_boost_round=40000,
feature_name=features,
categorical_feature=cat_features,
verbose_eval=100)
#!#############################################################################
#! PREDICTIONS
test = pd.read_csv('test.csv')
for f in cat_features:
for c in data[f].unique():
test[f] = np.where(test[f] == c, cat_dict[(f,c)], test[f])
test['target'] = final_model.predict(test[features])