-
Notifications
You must be signed in to change notification settings - Fork 0
/
sunny_tree_method_bs1.py
265 lines (200 loc) · 9.88 KB
/
sunny_tree_method_bs1.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# -*- coding: utf-8 -*-
# @Time : 2018/5/13 下午2:01
# @Author : Zhixin Piao
# @Email : [email protected]
import numpy as np
import matplotlib.pyplot as plt
import pickle
import lightgbm as lgb
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import SMOTE, ADASYN
from sklearn.metrics import confusion_matrix
from sklearn import tree
def load_data(data_path):
"""
:param data_path:
:return: data_package = {
feature_standard_weight_list: 55
train_input: (7323, 55)
train_target: (7323, 2)
val_input: (814, 55)
val_target: (814, 2)
}
"""
with open(data_path, 'rb') as f:
data_package = pickle.load(f)
return data_package
def compute_profit(pred_recommend, gt):
"""
:param pred_recommend: [N,] value in {0, 1}
:param gt: [N, 2]
:return profit: float
"""
profit = ((gt[:, 1] - 30) * pred_recommend).sum()
return profit
def compute_accuracy(pred_recommend, gt):
"""
:param pred_recommend: (N, )
:param gt: (N, 2)
:return accuracy float
"""
gt_responded, gt_profit = gt[:, 0], gt[:, 1]
gt_recommend = (gt_responded == 1) * (gt_profit > 30)
sample_num = gt_recommend.shape[0]
gt_recommend_num = gt_recommend.sum()
total_precision = (pred_recommend == gt_recommend).sum() / sample_num
recommend_recall = (pred_recommend * gt_recommend).sum() / gt_recommend_num
return total_precision, recommend_recall
def normal_DT(data_type):
def test_param(min_samples_split, max_depth):
clf = DecisionTreeClassifier(random_state=0, criterion='entropy', min_samples_split=min_samples_split, max_depth=max_depth)
clf.fit(balanced_train_input, balanced_train_recommend)
pred_train_recommend = clf.predict(train_input)
pred_val_recommend = clf.predict(val_input)
tn, fp, fn, tp = confusion_matrix(val_recommend, pred_val_recommend).ravel()
print(tp, fn)
print(fp, tn)
print('tpr:', tp / (tp + fn), 'fpr:', fp / (tn + fp))
train_total_precision, train_recommend_recall = compute_accuracy(pred_train_recommend, train_target)
train_profit = compute_profit(pred_train_recommend, train_target)
val_total_precision, val_recommend_recall = compute_accuracy(pred_val_recommend, val_target)
val_profit = compute_profit(pred_val_recommend, val_target)
print('train_total_precision: %s, train_recommend_recall: %s' % (train_total_precision, train_recommend_recall))
print('train_profit: ', train_profit)
print('-' * 30)
print('val_total_precision: %s, val_recommend_recall: %s' % (val_total_precision, val_recommend_recall))
print('val_profit: ', val_profit)
result = {'train_TP': train_total_precision, 'train_RR': train_recommend_recall, 'train_profit': train_profit,
'val_TP': val_total_precision, 'val_RR': val_recommend_recall, 'val_profit': val_profit}
return result
data_package = load_data('new_data/train.data')
train_input, train_target = data_package['train_input'], data_package['train_target']
val_input, val_target = data_package['val_input'], data_package['val_target']
train_responded, train_profit = train_target[:, 0], train_target[:, 1]
train_recommend = (train_responded == 1) * (train_profit > 30)
val_responded, val_profit = val_target[:, 0], val_target[:, 1]
val_recommend = (val_responded == 1) * (val_profit > 30)
balanced_train_input, balanced_train_recommend = SMOTE().fit_sample(train_input, train_recommend.reshape(-1))
# val_profit_list = []
# for min_samples_split in range(5, 400, 50):
# for max_depth in range(1, 30):
# result = test_param(min_samples_split, max_depth)
# val_profit_list.append((result, min_samples_split, max_depth))
#
#
#
#
#
# val_profit_list = sorted(val_profit_list, key=lambda x: x[0]['val_profit'], reverse=True)
# print(val_profit_list[0])
result = test_param(5, 2)
print(result)
def lightGBM(data_type):
def test_param(num_leaves, max_depth, min_data_in_leaf):
# specify your configurations as a dict
params = {
'task': 'train',
'boosting_type': 'gbdt',
# 'max_depth': 1,
'objective': 'binary',
'metric': {'binary', 'auc'},
'num_leaves': num_leaves,
'max_depth': max_depth,
'learning_rate': 0.01,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0,
'num_iterations': 10000,
'min_data_in_leaf': min_data_in_leaf,
'is_unbalance': True
}
print('Start training...')
# train
gbm = lgb.train(params,
lgb_train,
num_boost_round=200,
valid_sets=lgb_eval,
early_stopping_rounds=5)
print('Save model...')
# save model to file
gbm.save_model('model.txt')
print('Start predicting...')
# predict
pred_train_recommend = gbm.predict(train_input, num_iteration=gbm.best_iteration) > 0.5
pred_val_recommend = gbm.predict(val_input, num_iteration=gbm.best_iteration) > 0.5
# eval
train_total_precision, train_recommend_recall = compute_accuracy(pred_train_recommend, train_target)
train_profit = compute_profit(pred_train_recommend, train_target)
val_total_precision, val_recommend_recall = compute_accuracy(pred_val_recommend, val_target)
val_profit = compute_profit(pred_val_recommend, val_target)
print('train_total_precision: %s, train_recommend_recall: %s' % (train_total_precision, train_recommend_recall))
print('train_profit: ', train_profit)
print('-' * 30)
print('val_total_precision: %s, val_recommend_recall: %s' % (val_total_precision, val_recommend_recall))
print('val_profit: ', val_profit)
result = {'train_TP': train_total_precision, 'train_RR': train_recommend_recall, 'train_profit': train_profit,
'val_TP': val_total_precision, 'val_RR': val_recommend_recall, 'val_profit': val_profit}
return result
# load or create your dataset
data_package = load_data('new_data/train.data')
train_input, train_target = data_package['train_input'], data_package['train_target']
val_input, val_target = data_package['val_input'], data_package['val_target']
train_responded, train_profit = train_target[:, 0], train_target[:, 1]
train_recommend = (train_responded == 1) * (train_profit > 30)
val_responded, val_profit = val_target[:, 0], val_target[:, 1]
val_recommend = (val_responded == 1) * (val_profit > 30)
# create dataset for lightgbm
lgb_train = lgb.Dataset(train_input, train_recommend)
lgb_eval = lgb.Dataset(val_input, val_recommend, reference=lgb_train)
# find max profit
val_profit_list = []
for max_depth in range(2, 20, 1):
for min_data_in_leaf in range(10, 200, 10):
num_leaves_step = 2 ** (max_depth - 1) // 20
num_leaves_step = 1 if num_leaves_step == 0 else num_leaves_step
for num_leaves in range(2 ** (max_depth - 1), 2 ** max_depth, num_leaves_step):
result = test_param(num_leaves, max_depth, min_data_in_leaf)
val_profit_list.append((result, num_leaves, max_depth, min_data_in_leaf))
val_profit_list = sorted(val_profit_list, key=lambda x: x[0]['val_profit'], reverse=True)
print(val_profit_list[0])
def random_forest():
def test_param(max_depth):
clf = RandomForestClassifier(max_depth=max_depth, random_state=0)
clf.fit(balanced_train_input, balanced_train_recommend)
pred_train_recommend = clf.predict(train_input)
pred_val_recommend = clf.predict(val_input)
train_total_precision, train_recommend_recall = compute_accuracy(pred_train_recommend, train_target)
train_profit = compute_profit(pred_train_recommend, train_target)
val_total_precision, val_recommend_recall = compute_accuracy(pred_val_recommend, val_target)
val_profit = compute_profit(pred_val_recommend, val_target)
print('train_total_precision: %s, train_recommend_recall: %s' % (train_total_precision, train_recommend_recall))
print('train_profit: ', train_profit)
print('-' * 30)
print('val_total_precision: %s, val_recommend_recall: %s' % (val_total_precision, val_recommend_recall))
print('val_profit: ', val_profit)
result = {'train_TP': train_total_precision, 'train_RR': train_recommend_recall, 'train_profit': train_profit,
'val_TP': val_total_precision, 'val_RR': val_recommend_recall, 'val_profit': val_profit}
return result
data_package = load_data('new2_data/train.data')
train_input, train_target = data_package['train_input'], data_package['train_target']
val_input, val_target = data_package['val_input'], data_package['val_target']
train_responded, train_profit = train_target[:, 0], train_target[:, 1]
train_recommend = (train_responded == 1) * (train_profit > 30)
val_responded, val_profit = val_target[:, 0], val_target[:, 1]
val_recommend = (val_responded == 1) * (val_profit > 30)
balanced_train_input, balanced_train_recommend = SMOTE().fit_sample(train_input, train_recommend.reshape(-1))
val_profit_list = []
for max_depth in range(1, 30):
result = test_param(max_depth)
val_profit_list.append((result, max_depth))
val_profit_list = sorted(val_profit_list, key=lambda x: x[0]['val_profit'], reverse=True)
print(val_profit_list[0])
def main():
normal_DT('sample')
# lightGBM('sample')
# random_forest()
if __name__ == '__main__':
main()