/
__init__.py
215 lines (187 loc) · 7.25 KB
/
__init__.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# -*- coding: utf-8 -*-
from ..Classifier import Classifier
class SVC(Classifier):
"""
See also
--------
sklearn.svm.SVC
http://scikit-learn.org/0.18/modules/generated/sklearn.svm.SVC.html
"""
SUPPORTED_METHODS = ['predict']
# @formatter:off
TEMPLATES = {
'c': {
'type': '{0}',
'arr': '{{{0}}}',
'arr[]': '{type} {name}[{n}] = {{{values}}};',
'arr[][]': '{type} {name}[{n}][{m}] = {{{values}}};',
'indent': ' ',
},
'java': {
'type': '{0}',
'arr': '{{{0}}}',
'arr[]': '{type}[] {name} = {{{values}}};',
'arr[][]': '{type}[][] {name} = {{{values}}};',
'indent': ' ',
},
'js': {
'type': '{0}',
'arr': '[{0}]',
'arr[]': 'var {name} = [{values}];',
'arr[][]': 'var {name} = [{values}];',
'indent': ' ',
},
'php': {
'type': '{0}',
'arr': '[{0}]',
'arr[]': '${name} = [{values}];',
'arr[][]': '${name} = [{values}];',
'indent': ' ',
},
'ruby': {
'type': '{0}',
'arr': '[{0}]',
'arr[]': '{name} = [{values}]',
'arr[][]': '{name} = [{values}]',
'indent': ' ',
},
}
# @formatter:on
def __init__(self, estimator, target_language='java',
target_method='predict', **kwargs):
"""
Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:param estimator : AdaBoostClassifier
An instance of a trained SVC estimator.
:param target_language : string
The target programming language.
:param target_method : string
The target method of the estimator.
"""
super(SVC, self).__init__(estimator, target_language=target_language,
target_method=target_method, **kwargs)
self.estimator = estimator
temp_type = self.temp('type')
temp_arr = self.temp('arr')
temp_arr_ = self.temp('arr[]')
temp_arr__ = self.temp('arr[][]')
params = estimator.get_params()
# Check kernel type:
kernels = ['linear', 'rbf', 'poly', 'sigmoid']
if params['kernel'] not in kernels:
msg = 'The kernel type is not supported.'
raise ValueError(msg)
# Check rbf gamma value:
if params['kernel'] == 'rbf' and params['gamma'] == 'auto':
msg = ('The classifier gamma value have to '
'be set (currently it is \'auto\').')
raise ValueError(msg)
self.params = params
self.n_features = len(estimator.support_vectors_[0])
self.svs_rows = estimator.n_support_
self.n_svs_rows = len(estimator.n_support_)
self.weights = self.temp('arr[]', skipping=True).format(
type='int', name='weights', values=', '.join([str(e) for e in self.svs_rows]),
n=len(self.svs_rows))
self.n_weights = len(self.svs_rows)
self.n_classes = len(estimator.classes_)
self.is_binary = self.n_classes == 2
self.prefix = 'binary' if self.is_binary else 'multi'
# Support vectors:
vectors = []
for vector in estimator.support_vectors_:
_vectors = [temp_type.format(self.repr(v)) for v in vector]
_vectors = temp_arr.format(', '.join(_vectors))
vectors.append(_vectors)
vectors = ', '.join(vectors)
vectors = self.temp('arr[][]', skipping=True).format(
type='double', name='vectors', values=vectors,
n=len(estimator.support_vectors_), m=len(estimator.support_vectors_[0]))
self.vectors = vectors
self.n_vectors = len(estimator.support_vectors_)
# Coefficients:
coeffs = []
for coeff in estimator.dual_coef_:
_coeffs = [temp_type.format(self.repr(c)) for c in coeff]
_coeffs = temp_arr.format(', '.join(_coeffs))
coeffs.append(_coeffs)
coeffs = ', '.join(coeffs)
coeffs = temp_arr__.format(type='double', name='coefficients',
values=coeffs, n=len(estimator.dual_coef_),
m=len(estimator.dual_coef_[0]))
self.coefficients = coeffs
self.n_coefficients = len(estimator.dual_coef_)
# Interceptions:
inters = [temp_type.format(self.repr(i)) for i in estimator._intercept_]
inters = ', '.join(inters)
inters = temp_arr_.format(type='double', name='intercepts',
values=inters, n=len(estimator._intercept_))
self.intercepts = inters
self.n_intercepts = len(estimator._intercept_)
# Kernel:
self.kernel = str(params['kernel'])[0] if self.target_language == 'c'\
else str(params['kernel'])
self.gamma = self.repr(self.params['gamma'])
self.coef0 = self.repr(self.params['coef0'])
self.degree = self.repr(self.params['degree'])
def export(self, class_name, method_name, use_repr=True, use_file=False):
"""
Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:param class_name: string, default: 'Brain'
The name of the class in the returned result.
:param method_name: string, default: 'predict'
The name of the method in the returned result.
:param use_repr : bool, default True
Whether to use repr() for floating-point values or not.
:param: use_file : bool, default False
Whether to store the estimator data in a separate file or not.
Returns
-------
:return : string
The transpiled algorithm with the defined placeholders.
"""
self.class_name = class_name
self.method_name = method_name
self.use_repr = use_repr
self.use_file = use_file
if self.target_method == 'predict':
return self.predict()
def predict(self):
"""
Transpile the predict method.
Returns
-------
:return : string
The transpiled predict method as string.
"""
self.method = self.create_method()
output = self.create_class()
return output
def create_method(self):
"""
Build the estimator method or function.
Returns
-------
:return out : string
The built method as string.
"""
n_indents = 1 if self.target_language in ['java', 'js',
'php', 'ruby'] else 0
method = self.temp('method', n_indents=n_indents,
skipping=True).format(**self.__dict__)
return method
def create_class(self):
"""
Build the estimator class.
Returns
-------
:return out : string
The built class as string.
"""
temp_class = self.temp('class')
out = temp_class.format(**self.__dict__)
return out