-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxgboost_solver.py
181 lines (147 loc) · 5.85 KB
/
xgboost_solver.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
import xgboost
from sklearn.grid_search import ParameterGrid
from functions import *
target_col = 'target'
""" Load data and change into used format"""
print('Load data')
train = pd.read_csv("numerai_training_data.csv")
target = train[target_col]
print(target.value_counts(normalize=True))
train = np.array(train.drop(target_col, axis=1))
# print(train)
test = pd.read_csv("numerai_tournament_data.csv")
test_results = test['t_id']
test_results.index = test['t_id']
test_results = pd.DataFrame(test_results)
test_results['probability'] = np.zeros((test.shape[0]))
del test_results['t_id']
del test['t_id']
test = np.array(test)
# print(test_results)
# print(test)
"""
CV
"""
best_score = 10
best_params = 0
best_train_prediction = 0
best_prediction = 0
meta_solvers_train = []
meta_solvers_test = []
best_train = 0
best_test = 0
param_grid = [
{'silent': [1],
'nthread': [3],
'eval_metric': ['logloss'],
'eta': [0.01],
'objective': ['binary:logistic'],
'max_depth': [6],
'min_child_weight': [1],
'num_round': [2000],
'gamma': [10],
'subsample': [0.5],
'colsample_bytree': [0.3],
'n_monte_carlo': [5],
'cv_n': [5],
'test_rounds_fac': [1.2],
'count_n': [0],
'mc_test': [True],
'special_feng': [0]
}
]
print('start CV')
early_stopping = 60
mc_round_list = []
mc_logloss_mean = []
mc_logloss_sd = []
params_list = []
print_results = []
for params in ParameterGrid(param_grid):
print(params)
params_list.append(params)
train_predictions = np.ones((train.shape[0],))
print('There are %d columns' % train.shape[1])
# CV
mc_auc = []
mc_round = []
mc_train_pred = []
for i_mc in range(params['n_monte_carlo']):
cv_n = params['cv_n']
kf = StratifiedKFold(target.values, n_folds=cv_n, shuffle=True, random_state=i_mc ** 3)
xgboost_rounds = []
for cv_train_index, cv_test_index in kf:
X_train, X_test = train[cv_train_index, :], train[cv_test_index, :]
y_train, y_test = target.iloc[cv_train_index].values, target.iloc[cv_test_index].values
# train machine learning
xg_train = xgboost.DMatrix(X_train, label=y_train)
xg_test = xgboost.DMatrix(X_test, label=y_test)
watchlist = [(xg_train, 'train'), (xg_test, 'test')]
num_round = params['num_round']
xgclassifier = xgboost.train(params, xg_train, num_round, watchlist, early_stopping_rounds=early_stopping);
xgboost_rounds.append(xgclassifier.best_iteration)
num_round = int(np.mean(xgboost_rounds))
print('The best n_rounds is %d' % num_round)
for cv_train_index, cv_test_index in kf:
X_train, X_test = train[cv_train_index, :], train[cv_test_index, :]
y_train, y_test = target.iloc[cv_train_index].values, target.iloc[cv_test_index].values
# train machine learning
xg_train = xgboost.DMatrix(X_train, label=y_train)
xg_test = xgboost.DMatrix(X_test, label=y_test)
watchlist = [(xg_train, 'train'), (xg_test, 'test')]
xgclassifier = xgboost.train(params, xg_train, num_round, watchlist);
# predict
predicted_results = xgclassifier.predict(xg_test)
train_predictions[cv_test_index] = predicted_results
print('AUC score ', log_loss(target.values, train_predictions))
mc_auc.append(log_loss(target.values, train_predictions))
mc_train_pred.append(train_predictions)
mc_round.append(num_round)
mc_train_pred = np.mean(np.array(mc_train_pred), axis=0)
mc_round_list.append(int(np.mean(mc_round)))
mc_logloss_mean.append(np.mean(mc_auc))
mc_logloss_sd.append(np.std(mc_auc))
print('The AUC range is: %.5f to %.5f and best n_round: %d' %
(mc_logloss_mean[-1] - mc_logloss_sd[-1], mc_logloss_mean[-1] + mc_logloss_sd[-1], mc_round_list[-1]))
print_results.append('The AUC range is: %.5f to %.5f and best n_round: %d' %
(mc_logloss_mean[-1] - mc_logloss_sd[-1], mc_logloss_mean[-1] + mc_logloss_sd[-1], mc_round_list[-1]))
print('For ', mc_auc)
print('The AUC of the average prediction is: %.5f' % log_loss(target.values, mc_train_pred))
meta_solvers_train.append(mc_train_pred)
# train machine learning
xg_train = xgboost.DMatrix(train, label=target.values)
xg_test = xgboost.DMatrix(test)
if params['mc_test']:
watchlist = [(xg_train, 'train')]
num_round = int(mc_round_list[-1] * params['test_rounds_fac'])
mc_pred = []
for i_mc in range(params['n_monte_carlo']):
params['seed'] = i_mc
xg_train = xgboost.DMatrix(train, label=target.values)
xg_test = xgboost.DMatrix(test)
watchlist = [(xg_train, 'train')]
xgclassifier = xgboost.train(params, xg_train, num_round, watchlist);
mc_pred.append(xgclassifier.predict(xg_test))
meta_solvers_test.append(np.mean(np.array(mc_pred), axis=0))
""" Write opt solution """
print('writing to file')
pd.DataFrame(mc_train_pred).to_csv('results/train_xgboost_d6_opt.csv')
test_results['probability'] = meta_solvers_test[-1]
test_results.to_csv("results/test_xgboost_d6_opt.csv")
if mc_logloss_mean[-1] < best_score:
print('new best log loss')
best_score = mc_logloss_mean[-1]
best_params = params
best_train_prediction = mc_train_pred
if params['mc_test']:
best_prediction = meta_solvers_test[-1]
print(best_score)
print(best_params)
print(params_list)
print(print_results)
print(mc_logloss_mean)
print(mc_logloss_sd)
"""
Final Solution
"""
# raw dataset: 0.6923