forked from VowpalWabbit/vowpal_wabbit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyvw.py
535 lines (447 loc) · 21.6 KB
/
pyvw.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import sys
import pylibvw
class SearchTask():
def __init__(self, vw, sch, num_actions):
self.vw = vw
self.sch = sch
self.blank_line = self.vw.example("")
self.blank_line.finish()
self.bogus_example = self.vw.example("1 | x")
def __del__(self):
self.bogus_example.finish()
pass
def _run(self, your_own_input_example):
pass
def _call_vw(self, fn, isTest):
self.bogus_example.set_test_only(isTest)
self.sch.set_structured_predict_hook(fn)
self.vw.learn(self.bogus_example)
self.vw.learn(self.blank_line) # this will cause our ._run hook to get called
def learn(self, data_iterator):
for my_example in data_iterator():
self._call_vw(lambda: self._run(my_example), isTest=False)
def predict(self, my_example):
self._output = None
def f(): self._output = self._run(my_example)
self._call_vw(f, isTest=True)
#if self._output is None:
# raise Exception('structured predict hook failed to return anything')
# don't raise this exception because your _run code legitimately
# _could_ return None!
return self._output
class vw(pylibvw.vw):
"""The pyvw.vw object is a (trivial) wrapper around the pylibvw.vw
object; you're probably best off using this directly and ignoring
the pylibvw.vw structure entirely."""
def __init__(self, argString=""):
"""Initialize the vw object. The (optional) argString is the
same as the command line arguments you'd use to run vw (eg,"--audit")"""
pylibvw.vw.__init__(self,argString)
self.finished = False
def get_weight(self, index, offset=0):
"""Given an (integer) index (and an optional offset), return
the weight for that position in the (learned) weight vector."""
return pylibvw.vw.get_weight(self, index, offset)
def learn(self, example):
"""Perform an online update; example can either be an example
object or a string (in which case it is parsed and then
learned on)."""
if isinstance(example, str):
self.learn_string(example)
else:
pylibvw.vw.learn(self, example)
def finish(self):
"""stop VW by calling finish (and, eg, write weights to disk)"""
if not self.finished:
pylibvw.vw.finish(self)
self.finished = True
def example(self, stringOrDict=None):
return example(self, stringOrDict)
def __del__(self):
self.finish()
def init_search_task(self, search_task):
sch = self.get_search_ptr()
def predict(examples, my_tag, oracle, condition=None, allowed=None, learner_id=0):
"""The basic (via-reduction) prediction mechanism. Several
variants are supported through this overloaded function:
'examples' can be a single example (interpreted as non-LDF
mode) or a list of examples (interpreted as LDF mode)
'my_tag' should be an integer id, specifying this prediction
'oracle' can be a single label (or in LDF mode a single
array index in 'examples') or a list of such labels if
the oracle policy is indecisive; if it is None, then
the oracle doesn't care
'condition' should be either: (1) a (tag,char) pair, indicating
to condition on the given tag with identifier from the char;
or (2) a (tag,len,char) triple, indicating to condition on
tag, tag-1, tag-2, ..., tag-len with identifiers char,
char+1, char+2, ..., char+len. or it can be a (heterogenous)
list of such things.
'allowed' can be None, in which case all actions are allowed;
or it can be list of valid actions (in LDF mode, this should
be None and you should encode the valid actions in 'examples')
'learner_id' specifies the underlying learner id
Returns a single prediction.
"""
if isinstance(examples, list):
raise Exception("LDF not yet supported in Python interface :(")
elif not (isinstance(examples, example) or isinstance(examples, pylibvw.example)):
raise TypeError("'examples' should be a pyvw example (or a pylibvw example)")
else:
P = sch.get_predictor(my_tag)
P.set_input(examples)
if isinstance(oracle, list): P.set_oracles(oracle)
elif isinstance(oracle, int): P.set_oracle(oracle)
else: raise TypeError('expecting oracle to be a list or an integer')
if condition is not None:
if not isinstance(condition, list): condition = [condition]
for c in condition:
if not isinstance(c, tuple): raise TypeError('item ' + str(c) + ' in condition list is malformed')
if len(c) == 2 and isinstance(c[0], int) and isinstance(c[1], str) and len(c[1]) == 1:
P.add_condition(c[0], c[1])
elif len(c) == 3 and isinstance(c[0], int) and isinstance(c[1], int) and isinstance(c[2], str) and len(c[2]) == 1:
P.add_condition_range(c[0], c[1], c[2])
else:
raise TypeError('item ' + str(c) + ' in condition list malformed')
if allowed is None: pass
elif isinstance(allowed, list):
P.set_alloweds(allowed)
else: raise TypeError('allowed argument wrong type')
if learner_id != 0: P.set_learner_id(learner_id)
return P.predict()
sch.predict = predict
num_actions = sch.get_num_actions()
return search_task(self, sch, num_actions)
class namespace_id():
"""The namespace_id class is simply a wrapper to convert between
hash spaces referred to by character (eg 'x') versus their index
in a particular example. Mostly used internally, you shouldn't
really need to touch this."""
def __init__(self, ex, id):
"""Given an example and an id, construct a namespace_id. The
id can either be an integer (in which case we take it to be an
index into ex.indices[]) or a string (in which case we take
the first character as the namespace id)."""
if isinstance(id, int): # you've specified a namespace by index
if id < 0 or id >= ex.num_namespaces():
raise Exception('namespace ' + str(id) + ' out of bounds')
self.id = id
self.ord_ns = ex.namespace(id)
self.ns = chr(self.ord_ns)
elif isinstance(id, str): # you've specified a namespace by string
if len(id) == 0:
id = ' '
self.id = None # we don't know and we don't want to do the linear search requered to find it
self.ns = id[0]
self.ord_ns = ord(self.ns)
else:
raise Exception("ns_to_characterord failed because id type is unknown: " + str(type(id)))
class example_namespace():
"""The example_namespace class is a helper class that allows you
to extract namespaces from examples and operate at a namespace
level rather than an example level. Mainly this is done to enable
indexing like ex['x'][0] to get the 0th feature in namespace 'x'
in example ex."""
def __init__(self, ex, ns, ns_hash=None):
"""Construct an example_namespace given an example and a
target namespace (ns should be a namespace_id)"""
if not isinstance(ns, namespace_id):
raise TypeError
self.ex = ex
self.ns = ns
self.ns_hash = None
def num_features_in(self):
"""Return the total number of features in this namespace."""
return self.ex.num_features_in(self.ns)
def __getitem__(self, i):
"""Get the feature/value pair for the ith feature in this
namespace."""
f = self.ex.feature(self.ns, i)
v = self.ex.feature_weight(self.ns, i)
return (f, v)
def iter_features(self):
"""iterate over all feature/value pairs in this namespace."""
for i in range(self.num_features_in()):
yield self[i]
def push_feature(self, feature, v=1.):
"""Add an unhashed feature to the current namespace (fails if
setup has already run on this example)."""
if self.ns_hash is None:
self.ns_hash = self.ex.vw.hash_space( self.ns )
self.ex.push_feature(self.ns, feature, v, self.ns_hash)
def pop_feature(self):
"""Remove the top feature from the current namespace; returns True
if a feature was removed, returns False if there were no
features to pop. Fails if setup has run."""
return self.ex.pop_feature(self.ns)
def push_features(self, ns, featureList):
"""Push a list of features to a given namespace. Each feature
in the list can either be an integer (already hashed) or a
string (to be hashed) and may be paired with a value or not
(if not, the value is assumed to be 1.0). See example.push_features
for examples."""
self.ex.push_features(self.ns, featureList)
class abstract_label:
"""An abstract class for a VW label."""
def __init__(self):
pass
def from_example(self, ex):
"""grab a label from a given VW example"""
raise Exception("from_example not yet implemented")
class simple_label(abstract_label):
def __init__(self, label=0., weight=1., initial=0., prediction=0.):
abstract_label.__init__(self)
if isinstance(label, example):
self.from_example(label)
else:
self.label = label
self.weight = weight
self.initial = initial
self.prediction = prediction
def from_example(self, ex):
self.label = ex.get_simplelabel_label()
self.weight = ex.get_simplelabel_weight()
self.initial = ex.get_simplelabel_initial()
self.prediction = ex.get_simplelabel_prediction()
def __str__(self):
s = str(self.label)
if self.weight != 1.:
s += ':' + self.weight
return s
class multiclass_label(abstract_label):
def __init__(self, label=1, weight=1., prediction=1):
abstract_label.__init__(self)
self.label = label
self.weight = weight
self.prediction = prediction
def from_example(self, ex):
self.label = ex.get_multiclass_label()
self.weight = ex.get_multiclass_weight()
self.prediction = ex.get_multiclass_prediction()
def __str__(self):
s = str(self.label)
if self.weight != 1.:
s += ':' + self.weight
return s
class cost_sensitive_label(abstract_label):
class wclass:
def __init__(self, label, cost=0., partial_prediction=0., wap_value=0.):
self.label = label
self.cost = cost
self.partial_prediction = partial_prediction
self.wap_value = wap_value
def __init__(self, costs=[], prediction=0):
abstract_label.__init__(self)
self.costs = costs
self.prediction = prediction
def from_example(self, ex):
self.prediction = ex.get_costsensitive_prediction()
self.costs = []
for i in range(ex.get_costsensitive_num_costs):
wc = wclass(ex.get_costsensitive_class(),
ex.get_costsensitive_cost(),
ex.get_costsensitive_partial_prediction(),
ex.get_costsensitive_wap_value())
self.costs.append(wc)
def __str__(self):
return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs])
class cbandits_label(abstract_label):
class wclass:
def __init__(self, label, cost=0., partial_prediction=0., probability=0.):
self.label = label
self.cost = cost
self.partial_prediction = partial_prediction
self.probability = probability
def __init__(self, costs=[], prediction=0):
abstract_label.__init__(self)
self.costs = costs
self.prediction = prediction
def from_example(self, ex):
self.prediction = ex.get_cbandits_prediction()
self.costs = []
for i in range(ex.get_cbandits_num_costs):
wc = wclass(ex.get_cbandits_class(),
ex.get_cbandits_cost(),
ex.get_cbandits_partial_prediction(),
ex.get_cbandits_probability())
self.costs.append(wc)
def __str__(self):
return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs])
class example(pylibvw.example):
"""The example class is a (non-trivial) wrapper around
pylibvw.example. Most of the wrapping is to make the interface
easier to use (by making the types safer via namespace_id) and
also with added python-specific functionality."""
def __init__(self, vw, initStringOrDict=None):
"""Construct a new example from vw. If initString is None, you
get an"empty" example which you can construct by hand (see, eg,
example.push_features). If initString is a string, then this
string is parsed as it would be from a VW data file into an
example (and "setup_example" is run)."""
if initStringOrDict is None:
pylibvw.example.__init__(self, vw)
self.setup_done = False
elif isinstance(initStringOrDict, str):
pylibvw.example.__init__(self, vw, initStringOrDict)
self.setup_done = True
elif isinstance(initStringOrDict, dict):
pylibvw.example.__init__(self, vw)
self.vw = vw
self.stride = vw.get_stride()
self.finished = False
self.setup_done = False
for ns_char,feats in initStringOrDict.iteritems():
self.push_features(ns_char, feats)
self.setup_example()
else:
raise TypeError('expecting string or dict as argument for example construction')
self.vw = vw
self.stride = vw.get_stride()
self.finished = False
def __del__(self):
self.finish()
def __enter__(self):
return self
def __exit__(self,typ,value,traceback):
self.finish()
return typ is None
def get_ns(self, id):
"""Construct a namespace_id from either an integer or string
(or, if a namespace_id is fed it, just return it directly)."""
if isinstance(id, namespace_id):
return id
else:
return namespace_id(self, id)
def __getitem__(self, id):
"""Get an example_namespace object associated with the given
namespace id."""
return example_namespace(self, self.get_ns(id))
def feature(self, ns, i):
"""Get the i-th hashed feature id in a given namespace (i can
range from 0 to self.num_features_in(ns)-1)"""
ns = self.get_ns(ns) # guaranteed to be a single character
f = pylibvw.example.feature(self, ns.ord_ns, i)
if self.setup_done:
f = (f - self.get_ft_offset()) / self.stride
return f
def feature_weight(self, ns, i):
"""Get the value(weight) associated with a given feature id in
a given namespace (i can range from 0 to
self.num_features_in(ns)-1)"""
return pylibvw.example.feature_weight(self, self.get_ns(ns).ord_ns, i)
def set_label_string(self, string):
"""Give this example a new label, formatted as a string (ala
the VW data file format)."""
pylibvw.example.set_label_string(self, self.vw, string)
def setup_example(self):
"""If this example hasn't already been setup (ie, quadratic
features constructed, etc.), do so."""
if self.setup_done:
raise Exception('trying to setup_example on an example that is already setup')
self.vw.setup_example(self)
self.setup_done = True
def learn(self):
"""Learn on this example (and before learning, automatically
call setup_example if the example hasn't yet been setup)."""
if not self.setup_done:
self.setup_example()
self.vw.learn(self)
def sum_feat_sq(self, ns):
"""Return the total sum feature-value squared for a given
namespace."""
return pylibvw.example.sum_feat_sq(self, self.get_ns(ns).ord_ns)
def num_features_in(self, ns):
"""Return the total number of features in a given namespace."""
return pylibvw.example.num_features_in(self, self.get_ns(ns).ord_ns)
def get_feature_id(self, ns, feature, ns_hash=None):
"""Return the hashed feature id for a given feature in a given
namespace. feature can either be an integer (already a feature
id) or a string, in which case it is hashed. Note that if
--hash all is on, then get_feature_id(ns,"5") !=
get_feature_id(ns, 5). If you've already hashed the namespace,
you can optionally provide that value to avoid re-hashing it."""
if isinstance(feature, int):
return feature
if isinstance(feature, str):
if ns_hash is None:
ns_hash = self.vw.hash_space( self.get_ns(ns).ns )
return self.vw.hash_feature(feature, ns_hash)
raise Exception("cannot extract feature of type: " + str(type(feature)))
def push_hashed_feature(self, ns, f, v=1.):
"""Add a hashed feature to a given namespace (fails if setup
has already run on this example). Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
pylibvw.example.push_hashed_feature(self, self.get_ns(ns).ord_ns, f, v)
def push_feature(self, ns, feature, v=1., ns_hash=None):
"""Add an unhashed feature to a given namespace (fails if
setup has already run on this example)."""
f = self.get_feature_id(ns, feature, ns_hash)
self.push_hashed_feature(ns, f, v)
def pop_feature(self, ns):
"""Remove the top feature from a given namespace; returns True
if a feature was removed, returns False if there were no
features to pop. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.pop_feature(self, self.get_ns(ns).ord_ns)
def push_namespace(self, ns):
"""Push a new namespace onto this example. You should only do
this if you're sure that this example doesn't already have the
given namespace. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
pylibvw.example.push_namespace(self, self.get_ns(ns).ord_ns)
def pop_namespace(self):
"""Remove the top namespace from an example; returns True if a
namespace was removed, or False if there were no namespaces
left. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.pop_namespace(self)
def ensure_namespace_exists(self, ns):
"""Check to see if a namespace already exists. If it does, do
nothing. If it doesn't, add it. Fails if setup has run."""
if self.setup_done: raise Exception("error: modification to example after setup")
return pylibvw.example.ensure_namespace_exists(self, self.get_ns(ns).ord_ns)
def push_features(self, ns, featureList):
"""Push a list of features to a given namespace. Each feature
in the list can either be an integer (already hashed) or a
string (to be hashed) and may be paired with a value or not
(if not, the value is assumed to be 1.0).
Examples:
ex.push_features('x', ['a', 'b'])
ex.push_features('y', [('c', 1.), 'd'])
space_hash = vw.hash_space( 'x' )
feat_hash = vw.hash_feature( 'a', space_hash )
ex.push_features('x', [feat_hash]) # note: 'x' should match the space_hash!
Fails if setup has run."""
ns = self.get_ns(ns)
self.ensure_namespace_exists(ns)
ns_hash = self.vw.hash_space(ns.ns)
for feature in featureList:
if isinstance(feature, int) or isinstance(feature, str):
f = feature
v = 1.
elif isinstance(feature, tuple) and len(feature) == 2:
f = feature[0]
v = feature[1]
else:
raise Exception('malformed feature to push of type: ' + str(type(feature)))
self.push_feature(ns, f, v, ns_hash)
def finish(self):
"""Tell VW that you're done with this example and it can
recycle it for later use."""
if not self.finished:
self.vw.finish_example(self)
self.finished = True
def iter_features(self):
"""Iterate over all feature/value pairs in this example (all
namespace included)."""
for ns_id in range( self.num_namespaces() ): # iterate over every namespace
ns = self.get_ns(ns_id)
for i in range(self.num_features_in(ns)):
f = self.feature(ns, i)
v = self.feature_weight(ns, i)
yield f,v
def get_label(self, label_class=simple_label):
"""Given a known label class (default is simple_label), get
the corresponding label structure for this example."""
return label_class(self)
#help(example)