forked from bigmlcom/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultimodel.py
More file actions
336 lines (290 loc) · 13.1 KB
/
Copy pathmultimodel.py
File metadata and controls
336 lines (290 loc) · 13.1 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# -*- coding: utf-8 -*-
#
# Copyright 2012-2025 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""A Multiple Local Predictive Model.
This module defines a Multiple Model to make predictions locally using multiple
local models.
This module can help you enormously to
reduce the latency for each prediction and let you use your models
offline.
from bigml.api import BigML
from bigml.multimodel import MultiModel
api = BigML()
model = MultiModel([api.get_model(model['resource']) for model in
api.list_models(query_string="tags__in=my_tag")
['objects']])
model.predict({"petal length": 3, "petal width": 1})
"""
import logging
import ast
from functools import partial
from bigml.exceptions import NoRootDecisionTree
from bigml.model import Model, cast_prediction, to_prediction
from bigml.model import LAST_PREDICTION
from bigml.util import get_predictions_file_name
from bigml.multivote import MultiVote
from bigml.multivote import PLURALITY_CODE, CONFIDENCE_CODE, PROBABILITY_CODE
from bigml.multivotelist import MultiVoteList
from bigml.io import UnicodeWriter, UnicodeReader
LOGGER = logging.getLogger('BigML')
def read_votes(votes_files, to_prediction_fn, data_locale=None):
"""Reads the votes found in the votes' files.
Returns a list of MultiVote objects containing the list of predictions.
votes_files parameter should contain the path to the files where votes
are stored
In to_prediction parameter we expect the method of a local model object
that casts the string prediction values read from the file to their
real type. For instance
>>> local_model = Model(model)
>>> prediction = local_model.to_prediction("1")
>>> isinstance(prediction, int)
True
>>> read_votes(["my_predictions_file"], local_model.to_prediction)
data_locale should contain the string identification for the locale
used in numeric formatting.
"""
votes = []
for order, votes_file in enumerate(votes_files):
index = 0
with UnicodeReader(votes_file) as rdr:
for row in rdr:
prediction = to_prediction_fn(row[0], data_locale=data_locale)
if index > (len(votes) - 1):
votes.append(MultiVote([]))
distribution = None
instances = None
if len(row) > 2:
distribution = ast.literal_eval(row[2])
instances = int(row[3])
try:
confidence = float(row[1])
except ValueError:
confidence = 0.0
prediction_row = [prediction, confidence, order,
distribution, instances]
votes[index].append_row(prediction_row)
index += 1
return votes
class MultiModel():
"""A multiple local model.
Uses a number of BigML remote models to build a local version that can be
used to generate predictions locally.
"""
def __init__(self, models, api=None, fields=None, class_names=None,
cache_get=None, operation_settings=None):
self.models = []
self.class_names = class_names
if isinstance(models, list):
if all(isinstance(model, Model) for model in models):
self.models = models
else:
for model in models:
# some models have no root info and should not be added
try:
self.models.append(Model(
model, api=api, fields=fields,
cache_get=cache_get,
operation_settings=operation_settings))
except NoRootDecisionTree:
pass
else:
try:
self.models.append(Model(
models, api=api, fields=fields,
cache_get=cache_get,
operation_settings=operation_settings))
except NoRootDecisionTree:
pass
def list_models(self):
"""Lists all the model/ids that compound the multi model.
"""
return [model.resource() for model in self.models]
def predict(self, input_data, method=PLURALITY_CODE, options=None,
missing_strategy=LAST_PREDICTION, full=False):
"""Makes a prediction based on the prediction made by every model.
The method parameter is a numeric key to the following combination
methods in classifications/regressions:
0 - majority vote (plurality)/ average: PLURALITY_CODE
1 - confidence weighted majority vote / error weighted:
CONFIDENCE_CODE
2 - probability weighted majority vote / average:
PROBABILITY_CODE
3 - threshold filtered vote / doesn't apply:
THRESHOLD_CODE
"""
votes = self.generate_votes(input_data,
missing_strategy=missing_strategy)
result = votes.combine(method=method, options=options, full=full)
if full:
unused_fields = set(input_data.keys())
for _, prediction in enumerate(votes.predictions):
unused_fields = unused_fields.intersection( \
set(prediction.get("unused_fields", [])))
if not isinstance(result, dict):
result = {"prediction": result}
result['unused_fields'] = list(unused_fields)
return result
def generate_votes(self, input_data,
missing_strategy=LAST_PREDICTION):
""" Generates a MultiVote object that contains the predictions
made by each of the models.
"""
votes = MultiVote([])
for model in self.models:
prediction_info = model.predict( \
input_data, missing_strategy=missing_strategy, full=True)
if model.boosting is not None:
votes.boosting = True
prediction_info.update( \
{"weight": model.boosting.get("weight")})
if model.boosting.get("objective_class") is not None:
prediction_info.update( \
{"class": model.boosting.get("objective_class")})
votes.append(prediction_info)
return votes
#pylint: disable=locally-disabled,protected-access
def _generate_votes(self, input_data, missing_strategy=LAST_PREDICTION,
unused_fields=None):
""" Generates a MultiVote object that contains the predictions
made by each of the models. Please note that this function
calls a _predict method which assumes input data has been
properly checked against the model fields. Only casting
to the correct type will be applied.
"""
votes = MultiVote([])
for model in self.models:
prediction_info = model._predict( \
input_data,
missing_strategy=missing_strategy, unused_fields=unused_fields)
if model.boosting is not None:
votes.boosting = True
prediction_info.update( \
{"weight": model.boosting.get("weight")})
if model.boosting.get("objective_class") is not None:
prediction_info.update( \
{"class": model.boosting.get("objective_class")})
votes.append(prediction_info)
return votes
def generate_votes_distribution(self,
input_data,
missing_strategy=LAST_PREDICTION,
method=PROBABILITY_CODE):
"""Generates a MultiVoteList object to contain the predictions
of a list of models as the list of classes and their predicted
probabilities or confidence.
"""
votes = []
for model in self.models:
model.class_names = self.class_names
if method == PLURALITY_CODE:
prediction_info = [0.0] * len(self.class_names)
prediction = model.predict(
input_data,
missing_strategy=missing_strategy,
full=False)
prediction_info[self.class_names.index(prediction)] = 1.0
else:
predict_method = model.predict_confidence \
if method == CONFIDENCE_CODE \
else model.predict_probability
prediction_info = predict_method(
input_data,
compact=True,
missing_strategy=missing_strategy)
votes.append(prediction_info)
return MultiVoteList(votes)
def batch_predict(self, input_data_list, output_file_path=None,
reuse=False,
missing_strategy=LAST_PREDICTION, headers=None,
to_file=True, use_median=False):
"""Makes predictions for a list of input data.
When the to_file argument is set to True, the predictions
generated for each model are stored in an output
file. The name of the file will use the following syntax:
model_[id of the model]__predictions.csv
For instance, when using model/50c0de043b563519830001c2 to predict,
the output file name will be
model_50c0de043b563519830001c2__predictions.csv
On the contrary, if it is False, the function returns a list
of MultiVote objects with the model's predictions.
"""
add_headers = (isinstance(input_data_list[0], list) and
headers is not None and
len(headers) == len(input_data_list[0]))
if not add_headers and not isinstance(input_data_list[0], dict):
raise ValueError("Input data list is not a dictionary or the"
" headers and input data information are not"
" consistent.")
order = 0
if not to_file:
votes = []
for model in self.models:
order += 1
out = None
if to_file:
output_file = get_predictions_file_name(model.resource_id,
output_file_path)
if reuse:
try:
with open(output_file):
continue
except IOError:
pass
try:
out = UnicodeWriter(output_file)
except IOError:
raise Exception("Cannot find %s directory." %
output_file_path)
if out:
out.open_writer()
for index, input_data in enumerate(input_data_list):
if add_headers:
input_data = dict(list(zip(headers, input_data)))
prediction = model.predict(input_data,
missing_strategy=missing_strategy,
full=True)
if model.regression:
# if median is to be used, we just replace the prediction
if use_median:
prediction["prediction"] = prediction["median"]
if to_file:
prediction = cast_prediction(prediction, to="list",
confidence=True,
distribution=True,
count=True)
out.writerow(prediction)
else:
if len(votes) <= index:
votes.append(MultiVote([]))
votes[index].append(prediction)
if out:
out.close_writer()
if not to_file:
return votes
return output_file_path
def batch_votes(self, predictions_file_path, data_locale=None):
"""Adds the votes for predictions generated by the models.
Returns a list of MultiVote objects each of which contains a list
of predictions.
"""
votes_files = []
for model in self.models:
votes_files.append(
get_predictions_file_name(
model.resource_id,
predictions_file_path))
return read_votes(
votes_files, partial(to_prediction, self.models[0]),
data_locale=data_locale)