-
Notifications
You must be signed in to change notification settings - Fork 10
/
InferenceLightGBM.py
169 lines (131 loc) · 5.65 KB
/
InferenceLightGBM.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
import pandas as pd
import numpy as np
import scipy
import json
from util import timeit
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
#
class InferenceLightGBM(object):
def __init__(self ,model_json,feature_names, cat_feature_map):
self.model_json = model_json
#print(self.model_json)
self.feature_names = self.model_json['feature_names']
self.categories = cat_feature_map
def predict(self ,X):
try:
columns = list(X.columns)
except :
print('{} should be a pandas.DataFrame'.format(X))
if self.model_json['feature_names'] == columns:
y = self._predict(X)
return y
else:
raise Exception("columns should be {}".format(self.feature_names) ,)
def _sigmoid(self ,z):
return 1.0 /( 1 + np.exp(-z))
def _predict(self ,X):
feat_names = self.feature_names
results = pd.Series(index=X.index)
trees = self.model_json['tree_info']
for idx in X.index:
X_sample = X.loc[idx:idx ,:]
leaf_values = 0.0
for tree in trees:
tree_structure = tree['tree_structure']
leaf_value = self._walkthrough_tree(tree_structure ,X_sample)
leaf_values += leaf_value
results[idx] = self._sigmoid(leaf_values)
return results
#
# def _walkthrough_tree(self ,tree_structure ,X_sample):
#
# if 'leaf_index' in tree_structure.keys():
#
# return tree_structure['leaf_value']
# else:
#
# split_feature = X_sample.iloc[0 ,tree_structure['split_feature']]
# decision_type = tree_structure['decision_type']
# threshold = tree_structure['threshold']
#
# if decision_type == '==':
# feat_name = self.feature_names[tree_structure['split_feature']]
# categories = self.categories[feat_name]
# category = categories[str(split_feature)]
# category = str(category)
# threshold = threshold.split('||')
# if category in threshold:
# tree_structure = tree_structure['left_child']
# else:
# tree_structure = tree_structure['right_child']
# return self._walkthrough_tree(tree_structure ,X_sample)
# # 数值特征
# elif decision_type == '<=':
# if split_feature <= threshold:
# tree_structure = tree_structure['left_child']
# else:
# tree_structure = tree_structure['right_child']
#
# return self._walkthrough_tree(tree_structure ,X_sample)
# else:
# print(tree_structure)
# print('decision_type: {} is not == or <='.format(decision_type))
# return None
def _walkthrough_tree(self ,tree_structure ,X_sample,tree_index):
if 'leaf_index' in tree_structure.keys():
return [tree_index + '_leaf_index_'+str(tree_structure['leaf_index'])]
else:
#print(tree_structure['split_feature'])
split_feature = '%f'%(X_sample[tree_structure['split_feature']])
decision_type = tree_structure['decision_type']
threshold = tree_structure['threshold']
split_index = tree_index + '_split_index_'+str(tree_structure['split_index'])
if decision_type == '==':
feat_name = self.feature_names[tree_structure['split_feature']]
categories = self.categories[feat_name]
category = categories[str(split_feature)]
category = str(category)
threshold = threshold.split('||')
print(category, threshold)
if category in threshold:
tree_structure = tree_structure['left_child']
else:
tree_structure = tree_structure['right_child']
tmp = self._walkthrough_tree(tree_structure, X_sample,tree_index)
return tmp #[split_index] + tmp
elif decision_type == '<=':
split_feature = float(split_feature)
if split_feature <= threshold:
tree_structure = tree_structure['left_child']
else:
tree_structure = tree_structure['right_child']
tmp = self._walkthrough_tree(tree_structure, X_sample,tree_index)
return tmp #[split_index] + tmp
else:
print('decision_type: {} is not == or <='.format(decision_type))
return [split_index]
def get_feaure(self,X_sample):
trees = self.model_json['tree_info']
features=[]
for tree in trees:
tree_structure = tree['tree_structure']
features.extend(self._walkthrough_tree(tree_structure, X_sample,"tree_index_"+str(tree["tree_index"])))
return features
def get_node_id_feature_sparse(self,X):
pool = ThreadPool(40)
#results = map(self.get_feaure, np.array(X.values))
results = pool.map(self.get_feaure, np.array(X.values))
results = list(results)
#print(results)
#results = np.array(results)
#print(results)
results = pd.DataFrame(results)
print(results.columns)
print("-------------")
results = pd.SparseDataFrame(pd.get_dummies(results)).astype("float")
print(results)
# columns = results.columns
# results = scipy.sparse.csr_matrix(results)
print(results.columns)
return results