test.py 8.89 KB
Newer Older
wxchan's avatar
wxchan committed
1
2
# coding: utf-8
# pylint: skip-file
Guolin Ke's avatar
Guolin Ke committed
3
import ctypes
wxchan's avatar
wxchan committed
4
import os
Guolin Ke's avatar
Guolin Ke committed
5
import sys
Guolin Ke's avatar
Guolin Ke committed
6
7

import numpy as np
8
import pytest
Guolin Ke's avatar
Guolin Ke committed
9
10
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__)))
Guolin Ke's avatar
Guolin Ke committed
18
    dll_path = [curr_path, os.path.join(curr_path, '../../'), os.path.join(curr_path, '../../lib/')]
Guolin Ke's avatar
Guolin Ke committed
19
    if os.name == 'nt':
Guolin Ke's avatar
Guolin Ke committed
20
21
22
        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
23
    else:
Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
28
29
30
31
32
33
34
35
36
        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]
        raise Exception('Cannot find lightgbm Library in following paths: ' + ','.join(dll_path))
    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
37
38
    return lib

wxchan's avatar
wxchan committed
39

Guolin Ke's avatar
Guolin Ke committed
40
41
LIB = LoadDll()

Guolin Ke's avatar
Guolin Ke committed
42
43
LIB.LGBM_GetLastError.restype = ctypes.c_char_p

44
45
46
47
48
49
dtype_float32 = 0
dtype_float64 = 1
dtype_int32 = 2
dtype_int64 = 3


Guolin Ke's avatar
Guolin Ke committed
50
51
52
def c_array(ctype, values):
    return (ctype * len(values))(*values)

wxchan's avatar
wxchan committed
53

Guolin Ke's avatar
Guolin Ke committed
54
def c_str(string):
Guolin Ke's avatar
Guolin Ke committed
55
    return ctypes.c_char_p(string.encode('ascii'))
Guolin Ke's avatar
Guolin Ke committed
56

wxchan's avatar
wxchan committed
57

58
@pytest.mark.skip
59
60
def test_load_from_file(filename, reference):
    ref = None
wxchan's avatar
wxchan committed
61
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
62
        ref = reference
63
    handle = ctypes.c_void_p()
wxchan's avatar
wxchan committed
64
65
66
67
    LIB.LGBM_DatasetCreateFromFile(
        c_str(filename),
        c_str('max_bin=15'),
        ref, ctypes.byref(handle))
Guolin Ke's avatar
Guolin Ke committed
68
    print(LIB.LGBM_GetLastError())
69
    num_data = ctypes.c_long()
wxchan's avatar
wxchan committed
70
    LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data))
71
    num_feature = ctypes.c_long()
wxchan's avatar
wxchan committed
72
73
    LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature))
    print('#data:%d #feature:%d' % (num_data.value, num_feature.value))
74
75
    return handle

wxchan's avatar
wxchan committed
76

77
@pytest.mark.skip
78
79
80
81
def test_save_to_binary(handle, filename):
    LIB.LGBM_DatasetSaveBinary(handle, c_str(filename))


82
@pytest.mark.skip
Guolin Ke's avatar
Guolin Ke committed
83
84
85
86
87
def test_load_from_csr(filename, reference):
    data = []
    label = []
    inp = open(filename, 'r')
    for line in inp.readlines():
wxchan's avatar
wxchan committed
88
89
        data.append([float(x) for x in line.split('\t')[1:]])
        label.append(float(line.split('\t')[0]))
Guolin Ke's avatar
Guolin Ke committed
90
91
92
93
94
95
    inp.close()
    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
96
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
97
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
98

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

wxchan's avatar
wxchan committed
119

120
@pytest.mark.skip
121
122
123
124
125
def test_load_from_csc(filename, reference):
    data = []
    label = []
    inp = open(filename, 'r')
    for line in inp.readlines():
wxchan's avatar
wxchan committed
126
127
        data.append([float(x) for x in line.split('\t')[1:]])
        label.append(float(line.split('\t')[0]))
128
129
130
131
132
133
    inp.close()
    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
134
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
135
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
136

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

wxchan's avatar
wxchan committed
157

158
@pytest.mark.skip
159
160
161
162
163
def test_load_from_mat(filename, reference):
    data = []
    label = []
    inp = open(filename, 'r')
    for line in inp.readlines():
wxchan's avatar
wxchan committed
164
165
        data.append([float(x) for x in line.split('\t')[1:]])
        label.append(float(line.split('\t')[0]))
166
167
168
169
170
171
    inp.close()
    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
172
    if reference is not None:
Guolin Ke's avatar
Guolin Ke committed
173
        ref = reference
Guolin Ke's avatar
Guolin Ke committed
174

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


193
@pytest.mark.skip
194
195
196
def test_free_dataset(handle):
    LIB.LGBM_DatasetFree(handle)

wxchan's avatar
wxchan committed
197

198
def test_dataset():
199
200
    train = test_load_from_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.train'), None)
    test = test_load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test'), train)
201
    test_free_dataset(test)
202
    test = test_load_from_csr(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test'), train)
203
    test_free_dataset(test)
204
    test = test_load_from_csc(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test'), train)
205
206
207
    test_free_dataset(test)
    test_save_to_binary(train, 'train.binary.bin')
    test_free_dataset(train)
wxchan's avatar
wxchan committed
208
    train = test_load_from_file('train.binary.bin', None)
209
    test_free_dataset(train)
wxchan's avatar
wxchan committed
210
211


212
def test_booster():
213
214
    train = test_load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.train'), None)
    test = test_load_from_mat(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test'), train)
215
    booster = ctypes.c_void_p()
216
217
    LIB.LGBM_BoosterCreate(train, c_str("app=binary metric=auc num_leaves=31 verbose=0"), ctypes.byref(booster))
    LIB.LGBM_BoosterAddValidData(booster, test)
218
    is_finished = ctypes.c_int(0)
wxchan's avatar
wxchan committed
219
    for i in range(1, 101):
wxchan's avatar
wxchan committed
220
        LIB.LGBM_BoosterUpdateOneIter(booster, ctypes.byref(is_finished))
Guolin Ke's avatar
Guolin Ke committed
221
        result = np.array([0.0], dtype=np.float64)
222
        out_len = ctypes.c_ulong(0)
Guolin Ke's avatar
Guolin Ke committed
223
        LIB.LGBM_BoosterGetEval(booster, 0, ctypes.byref(out_len), result.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
wxchan's avatar
wxchan committed
224
225
        if i % 10 == 0:
            print('%d Iteration test AUC %f' % (i, result[0]))
226
227
228
    LIB.LGBM_BoosterSaveModel(booster, -1, c_str('model.txt'))
    LIB.LGBM_BoosterFree(booster)
    test_free_dataset(train)
229
    test_free_dataset(test)
230
    booster2 = ctypes.c_void_p()
Guolin Ke's avatar
Guolin Ke committed
231
232
    num_total_model = ctypes.c_long()
    LIB.LGBM_BoosterCreateFromModelfile(c_str('model.txt'), ctypes.byref(num_total_model), ctypes.byref(booster2))
233
    data = []
234
    inp = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test'), 'r')
235
    for line in inp.readlines():
wxchan's avatar
wxchan committed
236
        data.append([float(x) for x in line.split('\t')[1:]])
237
238
    inp.close()
    mat = np.array(data)
Guolin Ke's avatar
Guolin Ke committed
239
    preb = np.zeros(mat.shape[0], dtype=np.float64)
Guolin Ke's avatar
Guolin Ke committed
240
    num_preb = ctypes.c_long()
241
    data = np.array(mat.reshape(mat.size), copy=False)
wxchan's avatar
wxchan committed
242
243
244
    LIB.LGBM_BoosterPredictForMat(
        booster2,
        data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),
245
246
247
248
249
250
        dtype_float64,
        mat.shape[0],
        mat.shape[1],
        1,
        1,
        50,
251
        c_str(''),
Guolin Ke's avatar
Guolin Ke committed
252
        ctypes.byref(num_preb),
253
        preb.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
254
    LIB.LGBM_BoosterPredictForFile(booster2, c_str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../examples/binary_classification/binary.test')), 0, 0, 50, c_str(''), c_str('preb.txt'))
255
    LIB.LGBM_BoosterFree(booster2)