test_.py 9.67 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
import sys
Guolin Ke's avatar
Guolin Ke committed
5

6
7
from platform import system

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

wxchan's avatar
wxchan committed
11

Guolin Ke's avatar
Guolin Ke committed
12
13
14
15
16
17
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__)))
18
19
    dll_path = [curr_path,
                os.path.join(curr_path, '../../'),
20
21
22
                os.path.join(curr_path, '../../python-package/lightgbm/compile'),
                os.path.join(curr_path, '../../python-package/compile'),
                os.path.join(curr_path, '../../lib/')]
23
    if system() in ('Windows', 'Microsoft'):
24
25
        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
26
27
28
        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
29
    else:
Guolin Ke's avatar
Guolin Ke committed
30
31
32
33
        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]
34
        raise Exception('Cannot find lightgbm library file in following paths:\n' + '\n'.join(dll_path))
Guolin Ke's avatar
Guolin Ke committed
35
36
37
38
39
40
41
42
    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
43
44
    return lib

wxchan's avatar
wxchan committed
45

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

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

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


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

wxchan's avatar
wxchan committed
59

Guolin Ke's avatar
Guolin Ke committed
60
def c_str(string):
Guolin Ke's avatar
Guolin Ke committed
61
    return ctypes.c_char_p(string.encode('ascii'))
Guolin Ke's avatar
Guolin Ke committed
62

wxchan's avatar
wxchan committed
63

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

wxchan's avatar
wxchan committed
82

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


87
def load_from_csr(filename, reference):
Guolin Ke's avatar
Guolin Ke committed
88
89
    data = []
    label = []
90
91
    with open(filename, 'r') as inp:
        for line in inp.readlines():
92
93
94
            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
95
96
97
98
99
    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
100
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
101
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
102

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

wxchan's avatar
wxchan committed
123

124
def load_from_csc(filename, reference):
125
126
    data = []
    label = []
127
128
    with open(filename, 'r') as inp:
        for line in inp.readlines():
129
130
131
            values = line.split('\t')
            data.append([float(x) for x in values[1:]])
            label.append(float(values[0]))
132
133
134
135
136
    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
137
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
138
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
139

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

wxchan's avatar
wxchan committed
160

161
def load_from_mat(filename, reference):
162
163
    data = []
    label = []
164
165
    with open(filename, 'r') as inp:
        for line in inp.readlines():
166
167
168
            values = line.split('\t')
            data.append([float(x) for x in values[1:]])
            label.append(float(values[0]))
169
170
171
172
173
    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
174
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
175
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
176

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


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

wxchan's avatar
wxchan committed
198

199
def test_dataset():
200
201
202
203
    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)
204
    free_dataset(test)
205
206
    test = load_from_csr(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
207
    free_dataset(test)
208
209
    test = load_from_csc(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                      '../../examples/binary_classification/binary.test'), train)
210
211
212
213
214
    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
215
216


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