"src/vscode:/vscode.git/clone" did not exist on "1d5f46f6e7704c1ce2a82cc1882e920d42cba7a3"
compat.py 4.48 KB
Newer Older
wxchan's avatar
wxchan committed
1
# coding: utf-8
2
"""Compatibility library."""
wxchan's avatar
wxchan committed
3
4
5
6
7
from __future__ import absolute_import

import inspect
import sys

8
9
import numpy as np

wxchan's avatar
wxchan committed
10
11
is_py3 = (sys.version_info[0] == 3)

12
"""Compatibility between Python2 and Python3"""
wxchan's avatar
wxchan committed
13
if is_py3:
14
    zip_ = zip
wxchan's avatar
wxchan committed
15
16
    string_type = str
    numeric_types = (int, float, bool)
wxchan's avatar
wxchan committed
17
    integer_types = (int, )
wxchan's avatar
wxchan committed
18
19
20
    range_ = range

    def argc_(func):
21
        """Count the number of arguments of a function."""
wxchan's avatar
wxchan committed
22
        return len(inspect.signature(func).parameters)
23
24

    def decode_string(bytestring):
25
        """Decode C bytestring to ordinary string."""
26
        return bytestring.decode('utf-8')
wxchan's avatar
wxchan committed
27
else:
28
    from itertools import izip as zip_
wxchan's avatar
wxchan committed
29
30
31
32
33
34
    string_type = basestring
    numeric_types = (int, long, float, bool)
    integer_types = (int, long)
    range_ = xrange

    def argc_(func):
35
        """Count the number of arguments of a function."""
wxchan's avatar
wxchan committed
36
37
        return len(inspect.getargspec(func).args)

38
    def decode_string(bytestring):
39
        """Decode C bytestring to ordinary string."""
40
41
        return bytestring

wxchan's avatar
wxchan committed
42
43
44
45
46
47
48
49
"""json"""
try:
    import simplejson as json
except (ImportError, SyntaxError):
    # simplejson does not support Python 3.2, it throws a SyntaxError
    # because of u'...' Unicode literals.
    import json

50

51
def json_default_with_numpy(obj):
52
    """Convert numpy classes to JSON serializable objects."""
53
54
55
56
57
58
59
60
    if isinstance(obj, (np.integer, np.floating, np.bool_)):
        return obj.item()
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    else:
        return obj


wxchan's avatar
wxchan committed
61
62
63
"""pandas"""
try:
    from pandas import Series, DataFrame
64
    from pandas.api.types import is_sparse as is_dtype_sparse
65
    PANDAS_INSTALLED = True
wxchan's avatar
wxchan committed
66
except ImportError:
67
68
    PANDAS_INSTALLED = False

wxchan's avatar
wxchan committed
69
    class Series(object):
70
71
        """Dummy class for pandas.Series."""

wxchan's avatar
wxchan committed
72
73
74
        pass

    class DataFrame(object):
75
76
        """Dummy class for pandas.DataFrame."""

wxchan's avatar
wxchan committed
77
78
        pass

79
80
    is_dtype_sparse = None

81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""matplotlib"""
try:
    import matplotlib
    MATPLOTLIB_INSTALLED = True
except ImportError:
    MATPLOTLIB_INSTALLED = False

"""graphviz"""
try:
    import graphviz
    GRAPHVIZ_INSTALLED = True
except ImportError:
    GRAPHVIZ_INSTALLED = False

95
96
"""datatable"""
try:
97
98
99
100
101
    import datatable
    if hasattr(datatable, "Frame"):
        DataTable = datatable.Frame
    else:
        DataTable = datatable.DataTable
102
103
104
105
106
107
108
109
110
111
    DATATABLE_INSTALLED = True
except ImportError:
    DATATABLE_INSTALLED = False

    class DataTable(object):
        """Dummy class for DataTable."""

        pass


wxchan's avatar
wxchan committed
112
113
114
115
116
"""sklearn"""
try:
    from sklearn.base import BaseEstimator
    from sklearn.base import RegressorMixin, ClassifierMixin
    from sklearn.preprocessing import LabelEncoder
117
    from sklearn.utils.class_weight import compute_sample_weight
118
    from sklearn.utils.multiclass import check_classification_targets
119
120
    from sklearn.utils.validation import (assert_all_finite, check_X_y,
                                          check_array, check_consistent_length)
wxchan's avatar
wxchan committed
121
    try:
wxchan's avatar
wxchan committed
122
        from sklearn.model_selection import StratifiedKFold, GroupKFold
123
        from sklearn.exceptions import NotFittedError
wxchan's avatar
wxchan committed
124
    except ImportError:
wxchan's avatar
wxchan committed
125
        from sklearn.cross_validation import StratifiedKFold, GroupKFold
126
        from sklearn.utils.validation import NotFittedError
wxchan's avatar
wxchan committed
127
    SKLEARN_INSTALLED = True
128
    from sklearn import __version__ as SKLEARN_VERSION
129
130
131
132
133
134
135
136
137
138
    _LGBMModelBase = BaseEstimator
    _LGBMRegressorBase = RegressorMixin
    _LGBMClassifierBase = ClassifierMixin
    _LGBMLabelEncoder = LabelEncoder
    LGBMNotFittedError = NotFittedError
    _LGBMStratifiedKFold = StratifiedKFold
    _LGBMGroupKFold = GroupKFold
    _LGBMCheckXY = check_X_y
    _LGBMCheckArray = check_array
    _LGBMCheckConsistentLength = check_consistent_length
139
    _LGBMAssertAllFinite = assert_all_finite
140
    _LGBMCheckClassificationTargets = check_classification_targets
141
    _LGBMComputeSampleWeight = compute_sample_weight
wxchan's avatar
wxchan committed
142
143
except ImportError:
    SKLEARN_INSTALLED = False
144
    SKLEARN_VERSION = '0.0.0'
145
146
147
148
149
150
151
152
153
154
    _LGBMModelBase = object
    _LGBMClassifierBase = object
    _LGBMRegressorBase = object
    _LGBMLabelEncoder = None
    LGBMNotFittedError = ValueError
    _LGBMStratifiedKFold = None
    _LGBMGroupKFold = None
    _LGBMCheckXY = None
    _LGBMCheckArray = None
    _LGBMCheckConsistentLength = None
155
    _LGBMAssertAllFinite = None
156
    _LGBMCheckClassificationTargets = None
157
    _LGBMComputeSampleWeight = None
158
159
160
161


# DeprecationWarning is not shown by default, so let's create our own with higher level
class LGBMDeprecationWarning(UserWarning):
162
163
    """Custom deprecation warning."""

164
    pass