-
Notifications
You must be signed in to change notification settings - Fork 3
/
vwoptimize.py
executable file
·4130 lines (3255 loc) · 131 KB
/
vwoptimize.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
"""Wrapper for Vowpal Wabbit that does cross-validation and hyper-parameter tuning"""
__version__ = '0.10.2dev'
__gitdescribe__ = 'GIT'
import sys
import os
import optparse
import traceback
import math
import csv
import re
import subprocess
import time
import json
import pprint
import unicodedata
from itertools import izip, izip_longest
from collections import deque
from pipes import quote
import numpy as np
try:
import threading
except Exception:
import dummy_threading as threading
csv.field_size_limit(10000000)
MINIMUM_LOG_IMPORTANCE = 1
TMPID = str(os.getpid())
TMP_PREFIX = None
KEEPTMP = False
STDIN_NAMES = ('/dev/stdin', '-')
STDOUT_NAMES = ('/dev/stdout', 'stdout')
VW_CMD = 'vw'
VOWPAL_WABBIT_ERRORS = "error|won't work right|errno|can't open|vw::vw_exception|need a cache file for multiple passes|cannot be specified"
DEFAULT_COLUMNSPEC = 'y,text,*'
METRIC_FORMAT = 'mean'
DEFAULT_METRICS = ['vw_average_loss']
AWK_TRAINSET = "awk '(NR - $fold) % KFOLDS != 0' VW |"
AWK_TESTSET = "awk '(NR - $fold) % KFOLDS == 0' VW |"
PERL_TRAINSET = "perl -nE 'if ((++$NR - $fold) % KFOLDS != 0) { print $_ }' VW |"
PERL_TESTSET = "perl -nE 'if ((++$NR - $fold) % KFOLDS == 0) { print $_ }' VW |"
options = None
if 'darwin' in sys.platform:
# awk is slow on Mac OS X
FOLDSCRIPT = 'perl'
else:
FOLDSCRIPT = 'awk'
def htmlparser_unescape(text, cache=[]):
if not cache:
import HTMLParser
cache.append(HTMLParser.HTMLParser())
return cache[0].unescape(text)
def _unlink_one(filename):
if not os.path.exists(filename):
return
try:
os.unlink(filename)
except Exception:
sys.stderr.write('Failed to unlink %r\n' % filename)
traceback.print_exc()
def unlink(*filenames):
if KEEPTMP:
return
for filename in filenames:
if not filename:
continue
if not isinstance(filename, basestring):
sys.exit('unlink() expects filenames as str or None, not %r\n' % (filename, ))
_unlink_one(filename)
# vowpal wabbit might create this and then not clean up
_unlink_one(filename + '.writing')
def kill(*jobs, **kwargs):
verbose = kwargs.pop('verbose', False)
assert not kwargs, kwargs
for job in jobs:
try:
if job.poll() is None:
if verbose:
log('Killing %s', job.pid)
job.kill()
except Exception, ex:
if 'no such process' not in str(ex):
sys.stderr.write('Failed to kill %r: %s\n' % (job, ex))
def open_regular_or_compressed(filename):
if filename is None:
return sys.stdin
if hasattr(filename, 'read'):
fobj = filename
else:
f = filename.lower()
ext = f.rsplit('.', 1)[-1]
if ext == 'gz':
import gzip
fobj = gzip.GzipFile(filename)
elif ext == 'bz2':
import bz2
fobj = bz2.BZ2File(filename)
elif ext == 'xz':
import lzma
fobj = lzma.open(filename)
else:
fobj = open(filename)
return fobj
def get_real_ext(filename):
filename = filename.rsplit('/', 1)[-1]
items = filename.rsplit('.', 2)
if len(items) >= 2 and items[-1] in 'gz bz2 xz'.split():
return items[-2]
return items[-1]
def get_temp_filename(suffix, counter=[0]):
counter[0] += 1
assert TMP_PREFIX
fname = '%s/%s.%s.%s' % (TMP_PREFIX, TMPID, counter[0], suffix)
assert not os.path.exists(fname), 'internal error: %s' % fname
return fname
log_lock = threading.RLock()
def log(s, *params, **kwargs):
importance = kwargs.pop('importance', None) or 0
assert not kwargs, kwargs
if importance >= MINIMUM_LOG_IMPORTANCE:
with log_lock:
try:
sys.stdout.flush()
except IOError:
pass
try:
s = s % params
except Exception:
s = '%s %r' % (s, params)
sys.stderr.write('%s\n' % (s, ))
def log_always(*args, **kwargs):
kwargs['importance'] = MINIMUM_LOG_IMPORTANCE
return log(*args, **kwargs)
def vw_failed(msg=''):
if msg:
sys.exit('%s failed: %s' % (VW_CMD, msg))
else:
sys.exit('%s failed' % (VW_CMD, ))
def flush_and_close(fileobj):
fileobj.flush()
try:
os.fsync(fileobj.fileno())
except OSError:
pass
fileobj.close()
def write_file(filename, data):
if isinstance(data, np.ndarray):
data = '\n'.join(str(x) for x in data)
elif isinstance(data, list):
data = ''.join(data)
else:
assert isinstance(data, str), type(data)
if filename in STDOUT_NAMES:
sys.stdout.write(data)
else:
fobj = open(filename, 'w')
fobj.write(data)
flush_and_close(fobj)
def get_format_from_filename(filename):
items = filename.lower().split('.')
for ext in reversed(items):
if ext in ['vw', 'csv', 'tsv', 'tab']:
return ext
class simple_reader(object):
def __init__(self, source):
self.source = source
def __iter__(self):
return self
def next(self):
row = self.source.next().split("\t")
row[-1] = row[-1].rstrip()
return row
def open_anything(source, format, ignoreheader, force_unbuffered=False):
source = open_regular_or_compressed(source)
if force_unbuffered:
# simply disabling buffering is not enough, see this for details: http://stackoverflow.com/a/6556862
source = iter(source.readline, '')
if format == 'vw':
return source
if format == 'tsv':
reader = csv.reader(source, csv.excel_tab)
if ignoreheader:
reader.next()
elif format == 'csv':
reader = csv.reader(source, csv.excel)
if ignoreheader:
reader.next()
elif format == 'tab':
reader = simple_reader(source)
if ignoreheader:
reader.next()
else:
raise ValueError('format not supported: %s' % format)
return reader
def limited_repr(obj, limit=80):
s = repr(obj)
if len(s) >= limit:
s = s[:limit - 3] + '...'
return s
class PassThroughOptionParser(optparse.OptionParser):
def _process_args(self, largs, rargs, values):
while rargs:
try:
optparse.OptionParser._process_args(self, largs, rargs, values)
except (optparse.BadOptionError, optparse.AmbiguousOptionError), e:
largs.append(e.opt_str)
def _match_long_opt(self, opt):
# This disable shortcuts so that '--ignorecount' is not parsed '--ignore' which conflics with "vw --ignore"
if opt in self._long_opt:
return opt
raise optparse.BadOptionError(opt)
def system(cmd, importance=1, repeat_on_error=0):
if isinstance(cmd, deque):
results = []
for item in cmd:
r = system(item, importance=importance, repeat_on_error=repeat_on_error)
results.append(r)
return '\n'.join(results).strip()
sys.stdout.flush()
start = time.time()
popen = Popen(cmd, shell=True, importance=importance)
if popen.stdout is not None or popen.stderr is not None:
out, err = popen.communicate()
else:
out, err = '', ''
retcode = popen.wait()
if retcode:
log_always('%s [%.1fs] %s', '-' if retcode == 0 else '!', time.time() - start, get_command_name(cmd))
if retcode:
if repeat_on_error > 0:
return system(cmd, importance=importance, repeat_on_error=repeat_on_error - 1)
sys.exit(1)
return (out or '') + (err or '')
def split_file(source, nfolds=None, ignoreheader=False, importance=0, minfoldsize=10000):
if nfolds is None:
nfolds = 10
if isinstance(source, basestring):
ext = get_real_ext(source)
else:
ext = 'xxx'
if hasattr(source, 'seek'):
source.seek(0)
# XXX already have examples_count
total_lines = 0
for line in open_regular_or_compressed(source):
total_lines += 1
if hasattr(source, 'seek'):
source.seek(0)
source = open_regular_or_compressed(source)
if ignoreheader:
source.next()
total_lines -= 1
foldsize = int(math.ceil(total_lines / float(nfolds)))
foldsize = max(foldsize, minfoldsize)
nfolds = int(math.ceil(total_lines / float(foldsize)))
folds = []
current_fold = -1
count = foldsize
current_fileobj = None
total_count = 0
for line in source:
if count >= foldsize:
if current_fileobj is not None:
flush_and_close(current_fileobj)
current_fileobj = None
current_fold += 1
if current_fold >= nfolds:
break
fname = get_temp_filename('fold%s.%s' % (current_fold, ext))
current_fileobj = open(fname, 'w')
count = 0
folds.append(fname)
current_fileobj.write(line)
count += 1
total_count += 1
if current_fileobj is not None:
flush_and_close(current_fileobj)
if total_count != total_lines:
sys.exit('internal error: total_count=%r total_lines=%r source=%r' % (total_count, total_lines, source))
return folds, total_lines
def _workers(workers):
if workers is not None and workers <= 1:
return 1
if workers is None or workers <= 0:
import multiprocessing
return 1 + multiprocessing.cpu_count()
return workers
def die_if_parent_dies(signum=9):
if 'linux' not in sys.platform:
return
try:
import ctypes
libc = ctypes.CDLL('libc.so.6', use_errno=True)
PR_SET_PDEATHSIG = 1
result = libc.prctl(PR_SET_PDEATHSIG, signum)
if result == 0:
return True
else:
log('prctl failed: %s', os.strerror(ctypes.get_errno()))
except StandardError, ex:
sys.stderr.write(str(ex) + '\n')
def get_command_name(params):
if not isinstance(params, dict):
return str(params)
name = params.get('name', None)
args = params.get('args')
if isinstance(args, list):
args = ' '.join(args)
if name:
return '[%s] %s' % (name, args)
else:
return str(args)
def Popen(params, **kwargs):
command_name = get_command_name(params)
if isinstance(params, dict):
params = params.copy()
args = params.pop('args')
params.pop('name', None)
params.update(kwargs)
else:
args = params
params = kwargs
importance = params.pop('importance', None)
if importance is None:
importance = 0
params.setdefault('preexec_fn', die_if_parent_dies)
log('+ %s', command_name, importance=importance)
popen = subprocess.Popen(args, **params)
return popen
def run_subprocesses(cmds, workers=None, importance=None):
for item in cmds:
if isinstance(item, deque):
for subitem in item:
assert isinstance(subitem, dict), subitem
else:
assert isinstance(item, dict), item
workers = _workers(workers)
cmds_queue = deque(cmds)
queue = deque()
success = False
outputs = {}
try:
while queue or cmds_queue:
if cmds_queue and len(queue) <= workers:
cmd = cmds_queue.popleft()
if isinstance(cmd, deque):
this_cmd = cmd.popleft()
followup = cmd
else:
this_cmd = cmd
followup = None
popen = Popen(this_cmd, shell=True, importance=importance)
popen._cmd = this_cmd
popen._name = this_cmd.get('name', '')
popen._followup = followup
queue.append(popen)
else:
popen = queue.popleft()
if popen.stdout is not None or popen.stderr is not None:
out, err = popen.communicate()
out = (out or '') + (err or '')
outputs.setdefault(popen._name, []).append(out)
retcode = popen.wait()
if retcode:
log_always('failed: %s', popen._cmd.get('args', get_command_name(popen._cmd)))
return None, outputs
else:
log('%s %s', '-' if retcode == 0 else '!', get_command_name(popen._cmd), importance=importance)
if popen._followup:
cmds_queue.append(popen._followup)
success = True
finally:
if not success:
kill(*queue, verbose=True)
return success, outputs
def _as_dict(lst, name):
if isinstance(lst, list):
lst = ' '.join(lst).strip()
lst = re.sub('\s+', ' ', lst)
return {'args': lst, 'shell': True, 'name': name}
def get_vw_command(
to_cleanup,
source,
vw_args='',
initial_regressor=None,
final_regressor=None,
predictions=None,
raw_predictions=None,
audit=False,
readable_model=None,
only_test=False,
fix_cache_file=False,
name=''):
data_filename = ''
data_pipeline = ''
if source is None:
pass
elif isinstance(source, basestring):
if '|' in source:
data_pipeline = source
if not data_pipeline.strip().endswith('|'):
data_pipeline += ' |'
else:
assert os.path.exists(source), source
data_filename = '-d %s' % source
elif isinstance(source, list):
assert source and os.path.exists(source[0]), source
data_pipeline = 'cat %s |' % ' '.join(quote(x) for x in source)
else:
raise TypeError('Expected string or list, not %r' % (source, ))
intermediate_model_filename = final_regressor
final_options = []
if audit:
final_options += ['-a']
if readable_model:
final_options += ['--readable_model', readable_model]
vw_args = vw_args.split()
if fix_cache_file:
if '--cache_file' in vw_args:
sys.exit('Dont provide --cache_file, one will be added automatically.')
if '-c' in vw_args or '--cache_file' in vw_args:
remove_option(vw_args, '-c', 0)
remove_option(vw_args, '--cache_file', 1)
if final_regressor:
cache_file = final_regressor + '.cache'
else:
cache_file = get_temp_filename('cache')
vw_args.extend(['--cache_file', cache_file])
to_cleanup.append(cache_file)
training_command = [
data_pipeline,
VW_CMD,
data_filename,
'-i %s' % initial_regressor if initial_regressor else '',
'-f %s' % intermediate_model_filename if intermediate_model_filename else '',
'-p %s' % predictions if predictions else '',
'-r %s' % raw_predictions if raw_predictions else '',
'-t' if only_test else '',
] + vw_args
if only_test:
return _as_dict(training_command + final_options, name=name)
return deque([_as_dict(training_command + final_options, name=name)])
def vw_cross_validation(
vw_filename,
kfold,
vw_args,
vw_test_args,
workers=None,
with_predictions=False,
with_raw_predictions=False,
calc_num_features=False,
capture_output=False):
if hasattr(capture_output, '__contains__') and '' in capture_output:
capture_output = True
workers = _workers(workers)
commands = []
p_filenames = []
r_filenames = []
readable_models = []
to_cleanup = []
vw_args = vw_args.replace('--quiet', '')
# Split into folds is done like this (example for 3 folds)
# Example -> fold:
# 1 -> 1
# 2 -> 2
# 3 -> 3
# 4 -> 1
# and so on
if kfold is None:
trainset = vw_filename
testset = None
kfold = 1
else:
assert kfold > 1, kfold
if FOLDSCRIPT == 'awk':
trainset = AWK_TRAINSET
testset = AWK_TESTSET
elif FOLDSCRIPT == 'perl':
trainset = PERL_TRAINSET
testset = PERL_TESTSET
else:
raise AssertionError('foldscript=%r not understood' % FOLDSCRIPT)
trainset = trainset.replace('KFOLDS', str(kfold)).replace('VW', vw_filename)
testset = testset.replace('KFOLDS', str(kfold)).replace('VW', vw_filename)
model_prefix = get_temp_filename('model') + '.$fold'
model_filename = model_prefix + '.bin' if testset else None
if with_predictions:
p_filename = '%s.predictions' % model_prefix
else:
p_filename = None
if with_raw_predictions:
r_filename = '%s.raw' % model_prefix
else:
r_filename = None
if calc_num_features:
readable_model = model_prefix + '.readable'
else:
readable_model = None
cleanup_tmpl = []
base_training_command = get_vw_command(
cleanup_tmpl,
trainset,
vw_args=vw_args,
final_regressor=model_filename,
predictions=None if testset else p_filename,
raw_predictions=None if testset else r_filename,
readable_model=readable_model,
fix_cache_file=kfold > 1,
name='train' if testset else 'test')
for item in base_training_command:
if capture_output is True or item['name'] in capture_output:
item['stderr'] = subprocess.PIPE
else:
item['args'] += ' --quiet'
if testset:
testing_command = get_vw_command(
cleanup_tmpl,
testset,
vw_args=vw_test_args,
initial_regressor=model_filename,
predictions=p_filename,
raw_predictions=r_filename,
only_test=True,
fix_cache_file=kfold > 1,
name='test')
if capture_output is True or 'test' in capture_output:
testing_command['stderr'] = subprocess.PIPE
else:
testing_command['args'] += ' --quiet'
base_training_command.append(testing_command)
for item in base_training_command:
log("+ %s", item['args'])
commands = []
for this_fold in xrange(1, kfold + 1):
this_fold = str(this_fold)
training_command = deque([x.copy() for x in base_training_command])
for cmd in training_command:
cmd['args'] = cmd['args'].replace('$fold', this_fold)
commands.append(training_command)
for filename in [model_filename, p_filename, r_filename, readable_model] + cleanup_tmpl:
if not filename:
continue
filename = filename.replace('$fold', this_fold)
assert not os.path.exists(filename), filename
to_cleanup.append(filename)
if p_filename:
p_filenames.append(p_filename.replace('$fold', this_fold))
if r_filename:
r_filenames.append(r_filename.replace('$fold', this_fold))
if readable_model:
readable_models.append(readable_model.replace('$fold', this_fold))
try:
success, outputs = run_subprocesses(commands, workers=workers, importance=-1)
# check outputs first, the might be a valuable error message there
outputs = dict((key, [parse_vw_output(out) for out in value]) for (key, value) in outputs.items())
if not success:
vw_failed()
for name in to_cleanup:
if not os.path.exists(name):
vw_failed('missing %r' % (name, ))
predictions = []
for items in izip_longest(*[open(x) for x in p_filenames]):
predictions.extend([float(x.split()[0]) for x in items if x is not None])
if predictions:
if np.equal(0, np.max(np.abs(np.mod(predictions[:10000], 1)))):
predictions = np.array(predictions, dtype=int)
else:
predictions = np.array(predictions)
raw_predictions = []
for items in izip_longest(*[open(x) for x in r_filenames]):
raw_predictions.extend([x for x in items if x is not None])
num_features = [get_num_features(name) for name in readable_models]
return predictions, raw_predictions, num_features, outputs
finally:
unlink(*to_cleanup)
def extract_test_args(vw_args):
if isinstance(vw_args, basestring):
vw_args = vw_args.split()
test_args = []
loss_function = read_argument(vw_args, '--loss_function')
if loss_function:
test_args.append('--loss_function ' + loss_function)
test_opts = [
'--probabilities',
'--onethread',
]
for opt in test_opts:
if opt in vw_args:
test_args.append(opt)
return ' '.join(test_args)
def vw_validation(
to_cleanup,
vw_filename,
vw_validation_filename,
vw_args,
vw_test_args,
workers=None,
with_predictions=False,
with_raw_predictions=False,
calc_num_features=False,
capture_output=False):
assert os.path.exists(vw_validation_filename), vw_validation_filename
if hasattr(capture_output, '__contains__') and '' in capture_output:
capture_output = True
vw_args = vw_args.replace('--quiet', '')
model_prefix = get_temp_filename('model')
model_filename = model_prefix + '.bin'
to_cleanup.append(model_filename)
if with_predictions:
p_filename = '%s.predictions' % model_prefix
to_cleanup.append(p_filename)
else:
p_filename = None
if with_raw_predictions:
r_filename = '%s.raw' % model_prefix
to_cleanup.append(r_filename)
else:
r_filename = None
if calc_num_features:
readable_model = model_prefix + '.readable'
to_cleanup.append(readable_model)
else:
readable_model = None
command = get_vw_command(
to_cleanup,
vw_filename,
vw_args=vw_args,
final_regressor=model_filename,
predictions=None,
raw_predictions=None,
readable_model=readable_model,
fix_cache_file=True,
name='train')
for item in command:
if capture_output is True or item['name'] in capture_output:
item['stderr'] = subprocess.PIPE
else:
item['args'] += ' --quiet'
training_out = system(command, importance=-1, repeat_on_error=1)
outputs = {}
if training_out:
outputs['train'] = [parse_vw_output(training_out)]
testing_command = get_vw_command(
to_cleanup,
vw_validation_filename,
vw_args=vw_test_args,
initial_regressor=model_filename,
predictions=p_filename,
raw_predictions=r_filename,
only_test=True,
name='test')
if capture_output is True or 'test' in capture_output:
testing_command['stderr'] = subprocess.PIPE
else:
testing_command['args'] += ' --quiet'
validation_out = system(testing_command, importance=-1, repeat_on_error=1)
if validation_out:
outputs['test'] = [parse_vw_output(validation_out)]
for name in to_cleanup:
if not os.path.exists(name):
vw_failed('missing %r' % (name, ))
if p_filename:
predictions = []
for line in open(p_filename):
predictions.append(float(line.split()[0]))
predictions = np.array(predictions)
else:
predictions = []
if r_filename:
raw_predictions = open(r_filename).readlines()
else:
raw_predictions = []
if readable_model:
num_features = get_num_features(readable_model)
else:
num_features = None
return predictions, raw_predictions, num_features, outputs, model_filename
def get_num_features(filename):
counting = False
count = 0
for line in open(filename):
if counting:
count += 1
else:
if line.strip() == ':0':
counting = True
return count
def parse_vw_output(output):
result = {}
for line in output.split('\n'):
if line.count(' = ') == 1:
key, value = line.split(' = ')
key = key.replace(' ', '_').replace("'", '').lower()
result[key] = value
else:
if re.search(VOWPAL_WABBIT_ERRORS, line.lower()):
sys.exit('vw failed: %s' % line.strip())
return result
def _load_predictions(file, size=None, with_text=False, named_labels=None, with_weights=False, examples=None):
filename = file
if isinstance(file, list):
filename = file
elif hasattr(file, 'read'):
pass
elif isinstance(file, basestring):
if file in STDOUT_NAMES:
sys.exit('Will not read %s' % file)
file = open_regular_or_compressed(file)
else:
raise AssertionError(limited_repr(file))
result = []
result_text = []
importance_weights = [] if with_weights else None
for line in file:
try:
text = line.strip()
if with_text:
result_text.append(text)
items = text.split()
label = items[0]
if importance_weights is not None:
if len(items) >= 2:
w = items[1]
if w.startswith("'") or '|' in w:
w = 1.0
else:
w = float(w)
importance_weights.append(w)
if named_labels is not None:
if label not in named_labels:
sys.exit('Unexpected label %r from %r' % (label, filename))
result.append(label)
else:
result.append(float(label))
except:
sys.stderr.write('Error while parsing %r\nin %r\n' % (line, limited_repr(filename)))
raise
if examples is not None and len(result) >= examples:
break
if size is not None:
if len(result) < size:
sys.exit('Too few items in %s: found %r, expecting %r' % (limited_repr(filename), len(result), size))
if len(result) > size:
mult = int(len(result) / size)
if size * mult == len(result):
# if --passes N option was used, then the number of predictions will be N times higher
result = result[-size:]
else:
sys.exit('Too many items in %s: found %r, expecting multiply of %r' % (limited_repr(filename), len(result), size))
retvalue = [np.array(result)]
if with_text:
retvalue.append(result_text)
if with_weights:
if not importance_weights:
retvalue.append(None)
else:
if len(importance_weights) != len(result):
sys.exit('Could not parse importance weights')
importance_weights = np.array(importance_weights)
retvalue.append(importance_weights)
if len(retvalue) == 1:
return retvalue[0]
return tuple(retvalue)
class BaseParam(object):
PRINTABLE_KEYS = 'opt init min max values format extra omit'.split()
_cast = None
@classmethod
def cast(cls, value):
if value is None:
return None
if value == '':
return None
if cls._cast is None:
return value
return cls._cast(value)
def pack(self, value):
if self._pack is None:
return value
return self._pack(value)
def unpack(self, value):
if self._unpack is None:
return value
return self._unpack(value)
def __init__(self, opt, init=None, min=None, max=None, format=None, pack=None, unpack=None, extra=None, omit=None, merge=False):
self.opt = opt
self.init = self.cast(init)
self.min = self.cast(min)
self.max = self.cast(max)
self.format = format
self._pack = pack
self._unpack = unpack
self.extra = None
self.omit = omit
self.separator = '' if merge else ' '
def avg(self, a, b):
result = self.cast(self.unpack((self.pack(self.min) + self.pack(self.max)) / 2.0))