Debian Codegraph @

tests/sklearn_test.py

raw
1 import pytest
2
3 try:
4 import numpy as np
5 import sklearn.datasets
6 from sklearn.linear_model import LogisticRegression
7 from sklearn.tree import DecisionTreeClassifier
8 except ImportError:
9 pytest.skip('sklearn is not available', allow_module_level=True)
10
11 import jsonpickle
12 import jsonpickle.ext.numpy
13
14
15 @pytest.fixture(scope='module', autouse=True)
16 def numpy_extension():
17 """Initialize the numpy extension for this test module"""
18 jsonpickle.ext.numpy.register_handlers()
19 yield # control to the test function.
20 jsonpickle.ext.numpy.unregister_handlers()
21
22
23 def test_decision_tree():
24 # Create data.
25 np.random.seed(13)
26 x_values = np.random.randint(low=0, high=10, size=12)
27 x = x_values.reshape(4, 3)
28 y_values = np.random.randint(low=0, high=2, size=4)
29 y = y_values.reshape(-1, 1)
30
31 # train model
32 classifier = DecisionTreeClassifier(max_depth=1)
33 classifier.fit(x, y)
34
35 # freeze and thaw
36 pickler = jsonpickle.pickler.Pickler()
37 unpickler = jsonpickle.unpickler.Unpickler()
38 actual = unpickler.restore(pickler.flatten(classifier))
39
40 assert isinstance(actual, classifier.__class__)
41 if hasattr(classifier, 'tree_'):
42 assert isinstance(actual.tree_, classifier.tree_.__class__)
43
44 # predict from thawed
45 array_values = np.array([1, 2, 3])
46 array = array_values.reshape(1, -1)
47 prediction = actual.predict(array)
48 assert prediction[0] == 1
49
50 assert actual.max_depth == classifier.max_depth
51 assert actual.score(x, y) == classifier.score(x, y)
52 if hasattr(classifier, 'get_depth'):
53 assert actual.get_depth() == classifier.get_depth()
54
55
56 def test_nested_array_serialization():
57 iris = sklearn.datasets.load_iris()
58 X = iris.data[:, :2]
59 y = (iris.target != 0) * 1
60
61 pipe = LogisticRegression(solver="lbfgs")
62 pipe.fit(X, y)
63 pipe.predict(X)
64
65 # Try serializing/deserializing.
66 # Pipe is a LogisticRegression object that contains a nested array
67 js = jsonpickle.dumps(pipe)
68 pipe2 = jsonpickle.loads(js)
69 # coef_ only appears on an instance that has already been fit to something
70 assert np.all(pipe.coef_ == pipe2.coef_)