compat.py 4.23 KB
Newer Older
wxchan's avatar
wxchan committed
1
2
# coding: utf-8
# pylint: disable = C0103
3
"""Compatibility library."""
wxchan's avatar
wxchan committed
4
5
6
7
8
from __future__ import absolute_import

import inspect
import sys

9
10
import numpy as np

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

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

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

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

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

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

wxchan's avatar
wxchan committed
43
44
45
46
47
48
49
50
"""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

51

52
def json_default_with_numpy(obj):
53
    """Convert numpy classes to JSON serializable objects."""
54
55
56
57
58
59
60
61
    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
62
63
64
"""pandas"""
try:
    from pandas import Series, DataFrame
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
81
82
83
84
85
86
87
88
89
90
91
92
"""matplotlib"""
try:
    import matplotlib
    MATPLOTLIB_INSTALLED = True
except ImportError:
    MATPLOTLIB_INSTALLED = False

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

93
94
95
96
97
98
99
100
101
102
103
104
105
"""datatable"""
try:
    from datatable import DataTable
    DATATABLE_INSTALLED = True
except ImportError:
    DATATABLE_INSTALLED = False

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

        pass


wxchan's avatar
wxchan committed
106
107
108
109
110
"""sklearn"""
try:
    from sklearn.base import BaseEstimator
    from sklearn.base import RegressorMixin, ClassifierMixin
    from sklearn.preprocessing import LabelEncoder
111
    from sklearn.utils.class_weight import compute_sample_weight
112
    from sklearn.utils.multiclass import check_classification_targets
113
114
    from sklearn.utils.validation import (assert_all_finite, check_X_y,
                                          check_array, check_consistent_length)
wxchan's avatar
wxchan committed
115
    try:
wxchan's avatar
wxchan committed
116
        from sklearn.model_selection import StratifiedKFold, GroupKFold
117
        from sklearn.exceptions import NotFittedError
wxchan's avatar
wxchan committed
118
    except ImportError:
wxchan's avatar
wxchan committed
119
        from sklearn.cross_validation import StratifiedKFold, GroupKFold
120
        from sklearn.utils.validation import NotFittedError
wxchan's avatar
wxchan committed
121
    SKLEARN_INSTALLED = True
122
123
124
125
126
127
128
129
130
131
    _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
132
    _LGBMAssertAllFinite = assert_all_finite
133
    _LGBMCheckClassificationTargets = check_classification_targets
134
    _LGBMComputeSampleWeight = compute_sample_weight
wxchan's avatar
wxchan committed
135
136
except ImportError:
    SKLEARN_INSTALLED = False
137
138
139
140
141
142
143
144
145
146
    _LGBMModelBase = object
    _LGBMClassifierBase = object
    _LGBMRegressorBase = object
    _LGBMLabelEncoder = None
    LGBMNotFittedError = ValueError
    _LGBMStratifiedKFold = None
    _LGBMGroupKFold = None
    _LGBMCheckXY = None
    _LGBMCheckArray = None
    _LGBMCheckConsistentLength = None
147
    _LGBMAssertAllFinite = None
148
    _LGBMCheckClassificationTargets = None
149
    _LGBMComputeSampleWeight = None
150
151
152
153


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

156
    pass