test_.py 9.66 KB
Newer Older
wxchan's avatar
wxchan committed
1
# coding: utf-8
Guolin Ke's avatar
Guolin Ke committed
2
import ctypes
wxchan's avatar
wxchan committed
3
import os
Guolin Ke's avatar
Guolin Ke committed
4

5
6
from platform import system

Guolin Ke's avatar
Guolin Ke committed
7
8
9
import numpy as np
from scipy import sparse

wxchan's avatar
wxchan committed
10

Guolin Ke's avatar
Guolin Ke committed
11
12
13
14
15
16
def find_lib_path():
    if os.environ.get('LIGHTGBM_BUILD_DOC', False):
        # we don't need lib_lightgbm while building docs
        return []

    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
17
18
    dll_path = [curr_path,
                os.path.join(curr_path, '../../'),
19
20
21
                os.path.join(curr_path, '../../python-package/lightgbm/compile'),
                os.path.join(curr_path, '../../python-package/compile'),
                os.path.join(curr_path, '../../lib/')]
22
    if system() in ('Windows', 'Microsoft'):
23
24
        dll_path.append(os.path.join(curr_path, '../../python-package/compile/Release/'))
        dll_path.append(os.path.join(curr_path, '../../python-package/compile/windows/x64/DLL/'))
Guolin Ke's avatar
Guolin Ke committed
25
26
27
        dll_path.append(os.path.join(curr_path, '../../Release/'))
        dll_path.append(os.path.join(curr_path, '../../windows/x64/DLL/'))
        dll_path = [os.path.join(p, 'lib_lightgbm.dll') for p in dll_path]
Guolin Ke's avatar
Guolin Ke committed
28
    else:
Guolin Ke's avatar
Guolin Ke committed
29
30
31
32
        dll_path = [os.path.join(p, 'lib_lightgbm.so') for p in dll_path]
    lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
    if not lib_path:
        dll_path = [os.path.realpath(p) for p in dll_path]
33
        raise Exception('Cannot find lightgbm library file in following paths:\n' + '\n'.join(dll_path))
Guolin Ke's avatar
Guolin Ke committed
34
35
36
37
38
39
40
41
    return lib_path


def LoadDll():
    lib_path = find_lib_path()
    if len(lib_path) == 0:
        return None
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
Guolin Ke's avatar
Guolin Ke committed
42
43
    return lib

wxchan's avatar
wxchan committed
44

Guolin Ke's avatar
Guolin Ke committed
45
46
LIB = LoadDll()

Guolin Ke's avatar
Guolin Ke committed
47
48
LIB.LGBM_GetLastError.restype = ctypes.c_char_p

49
50
51
52
53
54
dtype_float32 = 0
dtype_float64 = 1
dtype_int32 = 2
dtype_int64 = 3


Guolin Ke's avatar
Guolin Ke committed
55
56
57
def c_array(ctype, values):
    return (ctype * len(values))(*values)

wxchan's avatar
wxchan committed
58

Guolin Ke's avatar
Guolin Ke committed
59
def c_str(string):
60
    return ctypes.c_char_p(string.encode('utf-8'))
Guolin Ke's avatar
Guolin Ke committed
61

wxchan's avatar
wxchan committed
62

63
def load_from_file(filename, reference):
64
    ref = None
wxchan's avatar
wxchan committed
65
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
66
        ref = reference
67
    handle = ctypes.c_void_p()
wxchan's avatar
wxchan committed
68
69
70
    LIB.LGBM_DatasetCreateFromFile(
        c_str(filename),
        c_str('max_bin=15'),
71
72
        ref,
        ctypes.byref(handle))
Guolin Ke's avatar
Guolin Ke committed
73
    print(LIB.LGBM_GetLastError())
74
    num_data = ctypes.c_long()
wxchan's avatar
wxchan committed
75
    LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data))
76
    num_feature = ctypes.c_long()
wxchan's avatar
wxchan committed
77
    LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature))
78
    print('#data: %d #feature: %d' % (num_data.value, num_feature.value))
79
80
    return handle

wxchan's avatar
wxchan committed
81

82
def save_to_binary(handle, filename):
83
84
85
    LIB.LGBM_DatasetSaveBinary(handle, c_str(filename))


86
def load_from_csr(filename, reference):
Guolin Ke's avatar
Guolin Ke committed
87
88
    data = []
    label = []
89
90
    with open(filename, 'r') as inp:
        for line in inp.readlines():
91
92
93
            values = line.split('\t')
            data.append([float(x) for x in values[1:]])
            label.append(float(values[0]))
Guolin Ke's avatar
Guolin Ke committed
94
95
96
97
98
    mat = np.array(data)
    label = np.array(label, dtype=np.float32)
    csr = sparse.csr_matrix(mat)
    handle = ctypes.c_void_p()
    ref = None
wxchan's avatar
wxchan committed
99
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
100
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
101

wxchan's avatar
wxchan committed
102
103
104
105
    LIB.LGBM_DatasetCreateFromCSR(
        c_array(ctypes.c_int, csr.indptr),
        dtype_int32,
        c_array(ctypes.c_int, csr.indices),
Guolin Ke's avatar
Guolin Ke committed
106
        csr.data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),
wxchan's avatar
wxchan committed
107
        dtype_float64,
108
109
110
        ctypes.c_int64(len(csr.indptr)),
        ctypes.c_int64(len(csr.data)),
        ctypes.c_int64(csr.shape[1]),
wxchan's avatar
wxchan committed
111
112
113
        c_str('max_bin=15'),
        ref,
        ctypes.byref(handle))
114
    num_data = ctypes.c_long()
wxchan's avatar
wxchan committed
115
    LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data))
116
    num_feature = ctypes.c_long()
wxchan's avatar
wxchan committed
117
    LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature))
118
    LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)
119
    print('#data: %d #feature: %d' % (num_data.value, num_feature.value))
120
121
    return handle

wxchan's avatar
wxchan committed
122

123
def load_from_csc(filename, reference):
124
125
    data = []
    label = []
126
127
    with open(filename, 'r') as inp:
        for line in inp.readlines():
128
129
130
            values = line.split('\t')
            data.append([float(x) for x in values[1:]])
            label.append(float(values[0]))
131
132
133
134
135
    mat = np.array(data)
    label = np.array(label, dtype=np.float32)
    csr = sparse.csc_matrix(mat)
    handle = ctypes.c_void_p()
    ref = None
wxchan's avatar
wxchan committed
136
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
137
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
138

wxchan's avatar
wxchan committed
139
140
141
142
    LIB.LGBM_DatasetCreateFromCSC(
        c_array(ctypes.c_int, csr.indptr),
        dtype_int32,
        c_array(ctypes.c_int, csr.indices),
143
        csr.data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),
wxchan's avatar
wxchan committed
144
        dtype_float64,
145
146
147
        ctypes.c_int64(len(csr.indptr)),
        ctypes.c_int64(len(csr.data)),
        ctypes.c_int64(csr.shape[0]),
wxchan's avatar
wxchan committed
148
149
150
        c_str('max_bin=15'),
        ref,
        ctypes.byref(handle))
151
    num_data = ctypes.c_long()
wxchan's avatar
wxchan committed
152
    LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data))
153
    num_feature = ctypes.c_long()
wxchan's avatar
wxchan committed
154
    LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature))
155
    LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)
156
    print('#data: %d #feature: %d' % (num_data.value, num_feature.value))
157
158
    return handle

wxchan's avatar
wxchan committed
159

160
def load_from_mat(filename, reference):
161
162
    data = []
    label = []
163
164
    with open(filename, 'r') as inp:
        for line in inp.readlines():
165
166
167
            values = line.split('\t')
            data.append([float(x) for x in values[1:]])
            label.append(float(values[0]))
168
169
170
171
172
    mat = np.array(data)
    data = np.array(mat.reshape(mat.size), copy=False)
    label = np.array(label, dtype=np.float32)
    handle = ctypes.c_void_p()
    ref = None
wxchan's avatar
wxchan committed
173
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
174
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
175

176
177
    LIB.LGBM_DatasetCreateFromMat(
        data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),
178
179
180
181
        dtype_float64,
        mat.shape[0],
        mat.shape[1],
        1,
wxchan's avatar
wxchan committed
182
183
184
        c_str('max_bin=15'),
        ref,
        ctypes.byref(handle))
185
    num_data = ctypes.c_long()
wxchan's avatar
wxchan committed
186
    LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data))
187
    num_feature = ctypes.c_long()
wxchan's avatar
wxchan committed
188
    LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature))
Guolin Ke's avatar
Guolin Ke committed
189
    LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)
190
    print('#data: %d #feature: %d' % (num_data.value, num_feature.value))
Guolin Ke's avatar
Guolin Ke committed
191
    return handle
wxchan's avatar
wxchan committed
192
193


194
def free_dataset(handle):
195
196
    LIB.LGBM_DatasetFree(handle)

wxchan's avatar
wxchan committed
197

198
def test_dataset():
199
200
201
202
    train = load_from_file(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                        '../../examples/binary_classification/binary.train'), None)
    test = load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
203
    free_dataset(test)
204
205
    test = load_from_csr(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
206
    free_dataset(test)
207
208
    test = load_from_csc(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
209
210
211
212
213
    free_dataset(test)
    save_to_binary(train, 'train.binary.bin')
    free_dataset(train)
    train = load_from_file('train.binary.bin', None)
    free_dataset(train)
wxchan's avatar
wxchan committed
214
215


216
def test_booster():
217
218
219
220
    train = load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                       '../../examples/binary_classification/binary.train'), None)
    test = load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
221
    booster = ctypes.c_void_p()
222
223
224
225
    LIB.LGBM_BoosterCreate(
        train,
        c_str("app=binary metric=auc num_leaves=31 verbose=0"),
        ctypes.byref(booster))
226
    LIB.LGBM_BoosterAddValidData(booster, test)
227
    is_finished = ctypes.c_int(0)
228
    for i in range(1, 51):
wxchan's avatar
wxchan committed
229
        LIB.LGBM_BoosterUpdateOneIter(booster, ctypes.byref(is_finished))
Guolin Ke's avatar
Guolin Ke committed
230
        result = np.array([0.0], dtype=np.float64)
231
        out_len = ctypes.c_ulong(0)
232
233
234
235
236
        LIB.LGBM_BoosterGetEval(
            booster,
            0,
            ctypes.byref(out_len),
            result.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
wxchan's avatar
wxchan committed
237
        if i % 10 == 0:
238
            print('%d iteration test AUC %f' % (i, result[0]))
239
    LIB.LGBM_BoosterSaveModel(booster, 0, -1, c_str('model.txt'))
240
    LIB.LGBM_BoosterFree(booster)
241
242
    free_dataset(train)
    free_dataset(test)
243
    booster2 = ctypes.c_void_p()
Guolin Ke's avatar
Guolin Ke committed
244
    num_total_model = ctypes.c_long()
245
246
247
248
    LIB.LGBM_BoosterCreateFromModelfile(
        c_str('model.txt'),
        ctypes.byref(num_total_model),
        ctypes.byref(booster2))
249
    data = []
250
251
252
253
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           '../../examples/binary_classification/binary.test'), 'r') as inp:
        for line in inp.readlines():
            data.append([float(x) for x in line.split('\t')[1:]])
254
    mat = np.array(data)
Guolin Ke's avatar
Guolin Ke committed
255
    preb = np.zeros(mat.shape[0], dtype=np.float64)
Guolin Ke's avatar
Guolin Ke committed
256
    num_preb = ctypes.c_long()
257
    data = np.array(mat.reshape(mat.size), copy=False)
wxchan's avatar
wxchan committed
258
259
260
    LIB.LGBM_BoosterPredictForMat(
        booster2,
        data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),
261
262
263
264
265
        dtype_float64,
        mat.shape[0],
        mat.shape[1],
        1,
        1,
266
        25,
267
        c_str(''),
Guolin Ke's avatar
Guolin Ke committed
268
        ctypes.byref(num_preb),
269
        preb.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
270
271
    LIB.LGBM_BoosterPredictForFile(
        booster2,
272
273
        c_str(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           '../../examples/binary_classification/binary.test')),
274
275
        0,
        0,
276
        25,
277
278
        c_str(''),
        c_str('preb.txt'))
279
    LIB.LGBM_BoosterFree(booster2)