-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_xgboost.py
61 lines (46 loc) · 1.9 KB
/
test_xgboost.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
import tempfile
from functools import lru_cache
import numpy as np
import xgboost as xgb
from jackdaw_ml import loads, saves
from jackdaw_ml.artefact_decorator import artefacts
from jackdaw_ml.serializers.pickle import PickleSerializer
@artefacts({PickleSerializer: ["model"]})
class BasicXGBWrapper:
"""
XGBoost is zipsafe, so there's no real issue with using PickleSerializer over the Booster objects it provided.
For better performance, you can construct a custom XGB serializer.
"""
booster: xgb.Booster
@lru_cache(maxsize=1)
def example_data() -> xgb.DMatrix:
data = np.random.rand(500, 10) # 500 entities, each contains 10 features
label = np.random.randint(2, size=500) # binary target
return xgb.DMatrix(data, label=label)
@lru_cache(maxsize=1)
def example_data_raw() -> xgb.DMatrix:
data = np.random.rand(500, 10) # 500 entities, each contains 10 features
return xgb.DMatrix(data)
def np_float_equivalence(a: np.ndarray, b: np.ndarray) -> bool:
# Are `a` and `b` within a reasonable distance of each other, accounting for internal machine error?
return np.sum(a - b) <= np.finfo(np.float32).eps
def model_equivalent(m1: BasicXGBWrapper, m2: BasicXGBWrapper) -> bool:
with tempfile.NamedTemporaryFile("wb") as m1_f:
with tempfile.NamedTemporaryFile("wb") as m2_f:
m1_res = m1.model.predict(example_data_raw())
m2_res = m2.model.predict(example_data_raw())
m1_f.close()
m2_f.close()
m1.model.dump_model(str(m1_f.name))
m2.model.dump_model(str(m2_f.name))
return (
np_float_equivalence(m1_res, m2_res)
and open(m1_f.name).read() == open(m2_f.name).read()
)
def test_basic_wrapper():
m1 = BasicXGBWrapper()
m1.model = xgb.train({}, example_data())
model_id = saves(m1)
m2 = BasicXGBWrapper()
loads(m2, model_id)
assert model_equivalent(m1, m2)