forked from h2oai/h2o-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
h2o_methods.py
1730 lines (1519 loc) · 63.4 KB
/
h2o_methods.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
import os, sys, time, requests, zipfile, StringIO
import h2o_args
# from h2o_cmd import runInspect, infoFromSummary
import h2o_cmd, h2o_util
import h2o_browse as h2b
import h2o_print as h2p
from h2o_objects import H2O
from h2o_test import verboseprint, dump_json, check_sandbox_for_errors, get_sandbox_name, log
# print "h2o_methods"
def check_params_update_kwargs(params_dict, kw, function, print_params):
# only update params_dict..don't add
# throw away anything else as it should come from the model (propagating what RF used)
for k in kw:
if k in params_dict:
params_dict[k] = kw[k]
else:
raise Exception("illegal parameter '%s' in %s" % (k, function))
if print_params:
print "%s parameters:" % function, params_dict
sys.stdout.flush()
def get_cloud(self, noExtraErrorCheck=False, timeoutSecs=10):
# hardwire it to allow a 60 second timeout
a = self.do_json_request('Cloud.json', noExtraErrorCheck=noExtraErrorCheck, timeout=timeoutSecs)
version = a['version']
if version and version!='(unknown)' and version!='null' and version!='none':
if not version.startswith('2'):
h2p.red_print("h2o version at node[0] doesn't look like h2o version. (start with 2) %s" % version)
consensus = a['consensus']
locked = a['locked']
cloud_size = a['cloud_size']
cloud_name = a['cloud_name']
node_name = a['node_name']
node_id = self.node_id
verboseprint('%s%s %s%s %s%s %s%s %s%s' % (
"\tnode_id: ", node_id,
"\tcloud_size: ", cloud_size,
"\tconsensus: ", consensus,
"\tlocked: ", locked,
"\tversion: ", version,
))
return a
def h2o_log_msg(self, message=None, timeoutSecs=15):
if 1 == 0:
return
if not message:
message = "\n"
message += "\n#***********************"
message += "\npython_test_name: " + h2o_args.python_test_name
message += "\n#***********************"
params = {'message': message}
self.do_json_request('2/LogAndEcho', params=params, timeout=timeoutSecs)
def get_timeline(self):
return self.do_json_request('Timeline.json')
# Shutdown url is like a reset button. Doesn't send a response before it kills stuff
# safer if random things are wedged, rather than requiring response
# so request library might retry and get exception. allow that.
def shutdown_all(self):
try:
self.do_json_request('Shutdown.json', noExtraErrorCheck=True)
except:
pass
# don't want delayes between sending these to each node
# if you care, wait after you send them to each node
# Seems like it's not so good to just send to one node
# time.sleep(1) # a little delay needed?
return (True)
def put_value(self, value, key=None, repl=None):
return self.do_json_request(
'PutValue.json',
params={"value": value, "key": key, "replication_factor": repl},
extraComment=str(value) + "," + str(key) + "," + str(repl))
# {"Request2":0,"response_info":i
# {"h2o":"pytest-kevin-4530","node":"/192.168.0.37:54321","time":0,"status":"done","redirect_url":null},
# "levels":[null,null,null,null]}
# FIX! what is this for? R uses it. Get one per col? maybe something about enums
def levels(self, source=None):
return self.do_json_request(
'2/Levels2.json',
params={"source": source},
)
def export_files(self, print_params=True, timeoutSecs=60, **kwargs):
params_dict = {
'src_key': None,
'path': None,
'force': None,
}
check_params_update_kwargs(params_dict, kwargs, 'export_files', print_params)
return self.do_json_request(
'2/ExportFiles.json',
timeout=timeoutSecs,
params=params_dict,
)
def put_file(self, f, key=None, timeoutSecs=60):
if key is None:
key = os.path.basename(f)
### print "putfile specifying this key:", key
fileObj = open(f, 'rb')
resp = self.do_json_request(
'2/PostFile.json',
cmd='post',
timeout=timeoutSecs,
params={"key": key},
files={"file": fileObj},
extraComment=str(f))
verboseprint("\nput_file response: ", dump_json(resp))
fileObj.close()
return key
# noise is a 2-tuple ("StoreView", none) for url plus args for doing during poll to create noise
# so we can create noise with different urls!, and different parms to that url
# no noise if None
def poll_url(self, response,
timeoutSecs=10, retryDelaySecs=0.5, initialDelaySecs=0, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False, reuseFirstPollUrl=False, noPrint=False):
verboseprint('poll_url input: response:', dump_json(response))
### print "poll_url: pollTimeoutSecs", pollTimeoutSecs
### print "at top of poll_url, timeoutSecs: ", timeoutSecs
# for the rev 2 stuff..the job_key, destination_key and redirect_url are just in the response
# look for 'response'..if not there, assume the rev 2
def get_redirect_url(response):
url = None
params = None
# StoreView has old style, while beta_features
if 'response_info' in response:
response_info = response['response_info']
if 'redirect_url' not in response_info:
raise Exception("Response during polling must have 'redirect_url'\n%s" % dump_json(response))
if response_info['status'] != 'done':
redirect_url = response_info['redirect_url']
if redirect_url:
url = self.url(redirect_url)
params = None
else:
if response_info['status'] != 'done':
raise Exception(
"'redirect_url' during polling is null but status!='done': \n%s" % dump_json(response))
else:
if 'response' not in response:
raise Exception("'response' not in response.\n%s" % dump_json(response))
if response['response']['status'] != 'done':
if 'redirect_request' not in response['response']:
raise Exception("'redirect_request' not in response. \n%s" % dump_json(response))
url = self.url(response['response']['redirect_request'])
params = response['response']['redirect_request_args']
return (url, params)
# if we never poll
msgUsed = None
if 'response_info' in response: # trigger v2 for GBM always?
status = response['response_info']['status']
progress = response.get('progress', "")
else:
r = response['response']
status = r['status']
progress = r.get('progress', "")
doFirstPoll = status != 'done'
(url, params) = get_redirect_url(response)
# no need to recreate the string for messaging, in the loop..
if params:
paramsStr = '&'.join(['%s=%s' % (k, v) for (k, v) in params.items()])
else:
paramsStr = ''
# FIX! don't do JStack noise for tests that ask for it. JStack seems to have problems
noise_enable = noise and noise != ("JStack", None)
if noise_enable:
print "Using noise during poll_url:", noise
# noise_json should be like "Storeview"
(noise_json, noiseParams) = noise
noiseUrl = self.url(noise_json + ".json")
if noiseParams is None:
noiseParamsStr = ""
else:
noiseParamsStr = '&'.join(['%s=%s' % (k, v) for (k, v) in noiseParams.items()])
start = time.time()
count = 0
if initialDelaySecs:
time.sleep(initialDelaySecs)
# can end with status = 'redirect' or 'done'
# Update: on DRF2, the first RF redirects to progress. So we should follow that, and follow any redirect to view?
# so for v2, we'll always follow redirects?
# For v1, we're not forcing the first status to be 'poll' now..so it could be redirect or done?(NN score? if blocking)
# Don't follow the Parse redirect to Inspect, because we want parseResult['destination_key'] to be the end.
# note this doesn't affect polling with Inspect? (since it doesn't redirect ?
while status == 'poll' or doFirstPoll or (status == 'redirect' and 'Inspect' not in url):
count += 1
if ((time.time() - start) > timeoutSecs):
# show what we're polling with
emsg = "Exceeded timeoutSecs: %d secs while polling." % timeoutSecs + \
"status: %s, url: %s?%s" % (status, urlUsed, paramsUsedStr)
raise Exception(emsg)
if benchmarkLogging:
import h2o
h2o.cloudPerfH2O.get_log_save(benchmarkLogging)
# every other one?
create_noise = noise_enable and ((count % 2) == 0)
if create_noise:
urlUsed = noiseUrl
paramsUsed = noiseParams
paramsUsedStr = noiseParamsStr
msgUsed = "\nNoise during polling with"
else:
urlUsed = url
paramsUsed = params
paramsUsedStr = paramsStr
msgUsed = "\nPolling with"
print status, progress, urlUsed
time.sleep(retryDelaySecs)
response = self.do_json_request(fullUrl=urlUsed, timeout=pollTimeoutSecs, params=paramsUsed)
verboseprint(msgUsed, urlUsed, paramsUsedStr, "Response:", dump_json(response))
# hey, check the sandbox if we've been waiting a long time...rather than wait for timeout
if ((count % 6) == 0):
check_sandbox_for_errors(python_test_name=h2o_args.python_test_name)
if (create_noise):
# this guarantees the loop is done, so we don't need to worry about
# a 'return r' being interpreted from a noise response
status = 'poll'
progress = ''
else:
doFirstPoll = False
status = response['response_info']['status']
progress = response.get('progress', "")
# get the redirect url
if not reuseFirstPollUrl: # reuse url for all v1 stuff
(url, params) = get_redirect_url(response)
if noPoll:
return response
# won't print if we didn't poll
if msgUsed:
verboseprint(msgUsed, urlUsed, paramsUsedStr, "Response:", dump_json(response))
return response
# this is only for 2 (fvec)
def kmeans_view(self, model=None, timeoutSecs=30, **kwargs):
# defaults
params_dict = {
'_modelKey': model,
}
browseAlso = kwargs.get('browseAlso', False)
# only lets these params thru
check_params_update_kwargs(params_dict, kwargs, 'kmeans_view', print_params=True)
print "\nKMeans2ModelView params list:", params_dict
a = self.do_json_request('2/KMeans2ModelView.json', timeout=timeoutSecs, params=params_dict)
# kmeans_score doesn't need polling?
verboseprint("\nKMeans2Model View result:", dump_json(a))
if (browseAlso | h2o_args.browse_json):
print "Redoing the KMeans2ModelView through the browser, no results saved though"
h2b.browseJsonHistoryAsUrlLastMatch('KMeans2ModelView')
time.sleep(5)
return a
# additional params include: cols=.
# don't need to include in params_dict it doesn't need a default
# FIX! cols should be renamed in test for fvec
def kmeans(self, key, key2=None,
timeoutSecs=300, retryDelaySecs=0.2, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False, **kwargs):
# defaults
# KMeans has more params than shown here
# KMeans2 has these params?
# max_iter=100&max_iter2=1&iterations=0
params_dict = {
'initialization': 'Furthest',
'k': 1,
'source': key,
'destination_key': key2,
'seed': None,
'cols': None,
'ignored_cols': None,
'ignored_cols_by_name': None,
'max_iter': None,
'normalize': None,
'drop_na_cols': None,
}
if key2 is not None: params_dict['destination_key'] = key2
browseAlso = kwargs.get('browseAlso', False)
# only lets these params thru
check_params_update_kwargs(params_dict, kwargs, 'kmeans', print_params=True)
algo = '2/KMeans2'
print "\n%s params list:" % algo, params_dict
a1 = self.do_json_request(algo + '.json',
timeout=timeoutSecs, params=params_dict)
if noPoll:
return a1
a1 = self.poll_url(a1, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs,
noise=noise, benchmarkLogging=benchmarkLogging)
print "For now, always dumping the last polled kmeans result ..are the centers good"
print "\n%s result:" % algo, dump_json(a1)
# if we want to return the model view like the browser
if 1==0:
# HACK! always do a model view. kmeans last result isn't good? (at least not always)
a = self.kmeans_view(model=a1['model']['_key'], timeoutSecs=30)
verboseprint("\n%s model view result:" % algo, dump_json(a))
else:
a = a1
if (browseAlso | h2o_args.browse_json):
print "Redoing the %s through the browser, no results saved though" % algo
h2b.browseJsonHistoryAsUrlLastMatch(algo)
time.sleep(5)
return a
# params:
# header=1,
# header_from_file
# separator=1 (hex encode?
# exclude=
# noise is a 2-tuple: ("StoreView",params_dict)
def parse(self, key, key2=None,
timeoutSecs=300, retryDelaySecs=0.2, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False, **kwargs):
browseAlso = kwargs.pop('browseAlso', False)
# this doesn't work. webforums indicate max_retries might be 0 already? (as of 3 months ago)
# requests.defaults({max_retries : 4})
# https://github.com/kennethreitz/requests/issues/719
# it was closed saying Requests doesn't do retries. (documentation implies otherwise)
algo = "2/Parse2"
verboseprint("\n %s key: %s to key2: %s (if None, means default)" % (algo, key, key2))
# other h2o parse parameters, not in the defauls
# header
# exclude
params_dict = {
'blocking': None, # debug only
'source_key': key, # can be a regex
'destination_key': key2,
'parser_type': None,
'separator': None,
'header': None,
'single_quotes': None,
'header_from_file': None,
'exclude': None,
'delete_on_done': None,
'preview': None,
}
check_params_update_kwargs(params_dict, kwargs, 'parse', print_params=True)
# h2o requires header=1 if header_from_file is used. Force it here to avoid bad test issues
if kwargs.get('header_from_file'): # default None
kwargs['header'] = 1
if benchmarkLogging:
import h2o
h2o.cloudPerfH2O.get_log_save(initOnly=True)
a = self.do_json_request(algo + ".json", timeout=timeoutSecs, params=params_dict)
# Check that the response has the right Progress url it's going to steer us to.
verboseprint(algo + " result:", dump_json(a))
if noPoll:
return a
# noise is a 2-tuple ("StoreView, none) for url plus args for doing during poll to create noise
# no noise if None
verboseprint(algo + ' noise:', noise)
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs,
noise=noise, benchmarkLogging=benchmarkLogging)
verboseprint("\n" + algo + " result:", dump_json(a))
return a
def netstat(self):
return self.do_json_request('Network.json')
def linux_info(self, timeoutSecs=30):
return self.do_json_request("CollectLinuxInfo.json", timeout=timeoutSecs)
def jstack(self, timeoutSecs=30):
return self.do_json_request("JStack.json", timeout=timeoutSecs)
def network_test(self, tdepth=5, timeoutSecs=30):
a = self.do_json_request("2/NetworkTest.json", params={}, timeout=timeoutSecs)
verboseprint("\n network test:", dump_json(a))
return(a)
def jprofile(self, depth=5, timeoutSecs=30):
return self.do_json_request("2/JProfile.json", params={'depth': depth}, timeout=timeoutSecs)
def iostatus(self):
return self.do_json_request("IOStatus.json")
# turns enums into expanded binary features
def one_hot(self, source, timeoutSecs=30, **kwargs):
params = {
"source": source,
}
a = self.do_json_request('2/OneHot.json',
params=params,
timeout=timeoutSecs
)
check_sandbox_for_errors(python_test_name=h2o_args.python_test_name)
return a
# &offset=
# &view=
# FIX! need to have max > 1000?
def inspect(self, key, offset=None, view=None, max_column_display=1000, ignoreH2oError=False,
timeoutSecs=30):
params = {
"src_key": key,
"offset": offset,
# view doesn't exist for 2. let it be passed here from old tests but not used
}
a = self.do_json_request('2/Inspect2.json',
params=params,
ignoreH2oError=ignoreH2oError,
timeout=timeoutSecs
)
return a
# can take a useful 'filter'
# FIX! current hack to h2o to make sure we get "all" rather than just
# default 20 the browser gets. set to max # by default (1024)
# There is a offset= param that's useful also, and filter=
def store_view(self, timeoutSecs=60, print_params=False, **kwargs):
params_dict = {
# now we should default to a big number, so we see everything
'filter': None,
'view': 10000,
'offset': 0,
}
# no checking on legal kwargs?
params_dict.update(kwargs)
if print_params:
print "\nStoreView params list:", params_dict
a = self.do_json_request('StoreView.json',
params=params_dict,
timeout=timeoutSecs)
return a
def rebalance(self, timeoutSecs=180, **kwargs):
params_dict = {
# now we should default to a big number, so we see everything
'source': None,
'after': None,
'chunks': None,
}
params_dict.update(kwargs)
a = self.do_json_request('2/ReBalance.json',
params=params_dict,
timeout=timeoutSecs
)
verboseprint("\n rebalance result:", dump_json(a))
return a
def to_int(self, timeoutSecs=60, **kwargs):
params_dict = {
'src_key': None,
'column_index': None, # ugh. takes 1 based indexing
}
params_dict.update(kwargs)
a = self.do_json_request('2/ToInt2.json', params=params_dict, timeout=timeoutSecs)
verboseprint("\n to_int result:", dump_json(a))
return a
def to_enum(self, timeoutSecs=60, **kwargs):
params_dict = {
'src_key': None,
'column_index': None, # ugh. takes 1 based indexing
}
params_dict.update(kwargs)
a = self.do_json_request('2/ToEnum2.json', params=params_dict, timeout=timeoutSecs)
verboseprint("\n to_int result:", dump_json(a))
return a
def unlock(self, timeoutSecs=30):
a = self.do_json_request('2/UnlockKeys.json', params=None, timeout=timeoutSecs)
return a
# There is also a RemoveAck in the browser, that asks for confirmation from
# the user. This is after that confirmation.
# UPDATE: ignore errors on remove..key might already be gone due to h2o removing it now
# after parse
def remove_key(self, key, timeoutSecs=120):
a = self.do_json_request('Remove.json',
params={"key": key}, ignoreH2oError=True, timeout=timeoutSecs)
self.unlock()
return a
# this removes all keys!
def remove_all_keys(self, timeoutSecs=120):
a = self.do_json_request('2/RemoveAll.json', timeout=timeoutSecs)
return a
# only model keys can be exported?
def export_hdfs(self, source_key, path):
a = self.do_json_request('ExportHdfs.json',
params={"source_key": source_key, "path": path})
verboseprint("\nexport_hdfs result:", dump_json(a))
return a
def export_s3(self, source_key, bucket, obj):
a = self.do_json_request('ExportS3.json',
params={"source_key": source_key, "bucket": bucket, "object": obj})
verboseprint("\nexport_s3 result:", dump_json(a))
return a
# the param name for ImportFiles is 'file', but it can take a directory or a file.
# 192.168.0.37:54323/ImportFiles.html?file=%2Fhome%2F0xdiag%2Fdatasets
def import_files(self, path, timeoutSecs=180):
a = self.do_json_request('2/ImportFiles2.json',
timeout=timeoutSecs,
params={"path": path}
)
verboseprint("\nimport_files result:", dump_json(a))
return a
# 'destination_key', 'escape_nan' 'expression'
def exec_query(self, timeoutSecs=20, ignoreH2oError=False, print_params=False, **kwargs):
# only v2 now
params_dict = {
'str': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'exec_query', print_params=print_params)
a = self.do_json_request('2/Exec2.json',
timeout=timeoutSecs, ignoreH2oError=ignoreH2oError, params=params_dict)
verboseprint("\nexec_query result:", dump_json(a))
return a
def jobs_admin(self, timeoutSecs=120, **kwargs):
params_dict = {
# 'expression': None,
}
browseAlso = kwargs.pop('browseAlso', False)
params_dict.update(kwargs)
verboseprint("\njobs_admin:", params_dict)
a = self.do_json_request('Jobs.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\njobs_admin result:", dump_json(a))
return a
def jobs_cancel(self, timeoutSecs=120, **kwargs):
params_dict = {
'key': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'jobs_cancel', print_params=True)
a = self.do_json_request('Cancel.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\njobs_cancel result:", dump_json(a))
print "Cancelled job:", params_dict['key']
return a
def create_frame(self, timeoutSecs=120, **kwargs):
params_dict = {
'key': None,
'rows': None,
'cols': None,
'seed': None,
'randomize': None,
'value': None,
'real_range': None,
'binary_fraction': None,
'categorical_fraction': None,
'factors': None,
'integer_fraction': None,
'integer_range': None,
'binary_fraction': None,
'binary_ones_fraction': None,
'missing_fraction': None,
'response_factors': None,
'has_response': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'create_frame', print_params=True)
a = self.do_json_request('2/CreateFrame.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\ncreate_frame result:", dump_json(a))
return a
def insert_missing_values(self, timeoutSecs=120, **kwargs):
params_dict = {
'key': None,
'seed': None,
'missing_fraction': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'insert_missing_values', print_params=True)
a = self.do_json_request('2/InsertMissingValues.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\ninsert_missing_values result:", dump_json(a))
return a
def impute(self, timeoutSecs=120, **kwargs):
params_dict = {
'source': None,
'column': None,
'method': None, # mean, mode, median
'group_by': None, # comma separated column names
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'impute', print_params=True)
a = self.do_json_request('2/Impute.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\nimpute result:", dump_json(a))
return a
def frame_split(self, timeoutSecs=120, **kwargs):
params_dict = {
'source': None,
'ratios': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'frame_split', print_params=True)
a = self.do_json_request('2/FrameSplitPage.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\nframe_split result:", dump_json(a))
return a
def nfold_frame_extract(self, timeoutSecs=120, **kwargs):
params_dict = {
'source': None,
'nfolds': None,
'afold': None, # Split to extract
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'nfold_frame_extract', print_params=True)
a = self.do_json_request('2/NFoldFrameExtractPage.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\nnfold_frame_extract result:", dump_json(a))
return a
def gap_statistic(self, timeoutSecs=120, retryDelaySecs=1.0, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False,
print_params=True, noPrint=False, **kwargs):
params_dict = {
'source': None,
'destination_key': None,
'k_max': None,
'b_max': None,
'bootstrap_fraction': None,
'seed': None,
'cols': None,
'ignored_cols': None,
'ignored_cols_by_name': None,
}
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'gap_statistic', print_params=True)
start = time.time()
a = self.do_json_request('2/GapStatistic.json', timeout=timeoutSecs, params=params_dict)
if noPoll:
return a
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs, benchmarkLogging=benchmarkLogging,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs)
verboseprint("\ngap_statistic result:", dump_json(a))
a['python_elapsed'] = time.time() - start
a['python_%timeout'] = a['python_elapsed'] * 100 / timeoutSecs
return a
def speedrf(self, data_key, ntrees=50, max_depth=20, timeoutSecs=300,
retryDelaySecs=1.0, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False,
print_params=True, noPrint=False, **kwargs):
params_dict = {
'balance_classes': None,
'classification': 1,
'cols': None,
'destination_key': None,
'ignored_cols': None,
'ignored_cols_by_name': None,
'importance': 0,
'keep_cross_validation_splits': None,
'max_after_balance_size': None,
'max_depth': max_depth,
'mtries': -1.0,
'nbins': 1024.0,
'n_folds': None,
'ntrees': ntrees,
'oobee': 0,
'response': None,
'sample_rate': 0.67,
'sampling_strategy': 'RANDOM',
'score_pojo': None, # create the score pojo
'seed': -1.0,
'select_stat_type': 'ENTROPY', # GINI
'source': data_key,
'validation': None,
'verbose': None,
}
check_params_update_kwargs(params_dict, kwargs, 'SpeeDRF', print_params)
if print_params:
print "\n%s parameters:" % "SpeeDRF", params_dict
sys.stdout.flush()
rf = self.do_json_request('2/SpeeDRF.json', timeout=timeoutSecs, params=params_dict)
print "\n%s result:" % "SpeeDRF", dump_json(rf)
if noPoll:
print "Not polling SpeeDRF"
return rf
time.sleep(2)
rfView = self.poll_url(rf, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs,
noise=noise, benchmarkLogging=benchmarkLogging, noPrint=noPrint)
return rfView
# note ntree in kwargs can overwrite trees! (trees is legacy param)
def random_forest(self, data_key, trees=None,
timeoutSecs=300, retryDelaySecs=1.0, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False, rfView=True,
print_params=True, noPrint=False, **kwargs):
print "at top of random_forest, timeoutSec: ", timeoutSecs
algo = '2/DRF'
algoView = '2/DRFView'
params_dict = {
# 'model': None,
'balance_classes': None,
'build_tree_one_node': None,
'classification': 1,
'cols': None,
'destination_key': None,
'ignored_cols': None,
'ignored_cols_by_name': None,
'importance': 1, # enable variable importance by default
'max_after_balance_size': None,
'max_depth': None,
'min_rows': None, # how many rows in leaves for stopping condition
'mtries': None,
'nbins': None,
'ntrees': trees,
'n_folds': None,
'response': None,
'sample_rate': None,
'score_each_iteration': None,
'seed': None,
'source': data_key,
'validation': None,
}
if 'model_key' in kwargs:
kwargs['destination_key'] = kwargs['model_key'] # hmm..should we switch test to new param?
browseAlso = kwargs.pop('browseAlso', False)
check_params_update_kwargs(params_dict, kwargs, 'random_forest', print_params)
# on v2, there is no default response. So if it's none, we should use the last column, for compatibility
inspect = h2o_cmd.runInspect(key=data_key)
# response only takes names. can't use col index..have to look it up
# or add last col
# mnist can be col 0 for response!
if ('response' not in params_dict) or (params_dict['response'] is None):
params_dict['response'] = str(inspect['cols'][-1]['name'])
elif isinstance(params_dict['response'], int):
params_dict['response'] = str(inspect['cols'][params_dict['response']]['name'])
if print_params:
print "\n%s parameters:" % algo, params_dict
sys.stdout.flush()
# always follow thru to rfview?
rf = self.do_json_request(algo + '.json', timeout=timeoutSecs, params=params_dict)
print "\n%s result:" % algo, dump_json(rf)
# noPoll and rfView=False are similar?
if (noPoll or not rfView):
# just return for now
print "no rfView:", rfView, "noPoll", noPoll
return rf
# since we don't know the model key from the rf response, we just let rf redirect us to completion
# if we want to do noPoll, we have to name the model, so we know what to ask for when we do the completion view
# HACK: wait more for first poll?
time.sleep(5)
rfView = self.poll_url(rf, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs,
noise=noise, benchmarkLogging=benchmarkLogging, noPrint=noPrint)
return rfView
def random_forest_view(self, data_key=None, model_key=None, timeoutSecs=300,
retryDelaySecs=0.2, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, print_params=False, noPoll=False,
noPrint=False, **kwargs):
print "random_forest_view not supported in H2O fvec yet. hacking done response"
r = {'response': {'status': 'done'}, 'trees': {'number_built': 0}}
# return r
algo = '2/DRFModelView'
# No such thing as 2/DRFScore2
algoScore = '2/DRFScore2'
# is response_variable needed here? it shouldn't be
# do_json_request will ignore any that remain = None
params_dict = {
'_modelKey': model_key,
}
browseAlso = kwargs.pop('browseAlso', False)
# only update params_dict..don't add
# throw away anything else as it should come from the model (propagating what RF used)
for k in kwargs:
if k in params_dict:
params_dict[k] = kwargs[k]
if print_params:
print "\n%s parameters:" % algo, params_dict
sys.stdout.flush()
whichUsed = algo
# for drf2, you can't pass a new dataset here, compared to what you trained with.
# should complain or something if tried with a data_key
if data_key:
print "Can't pass a new data_key to random_forest_view for v2's DRFModelView. Not using"
a = self.do_json_request(whichUsed + ".json", timeout=timeoutSecs, params=params_dict)
verboseprint("\n%s result:" % whichUsed, dump_json(a))
if noPoll:
return a
# add a fake redirect_request and redirect_request_args
# to the RF response, to make it look like everyone else
rfView = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs,
noPrint=noPrint, noise=noise, benchmarkLogging=benchmarkLogging)
drf_model = rfView['drf_model']
numberBuilt = drf_model['N']
# want to double check all this because it's new
# and we had problems with races/doneness before
errorInResponse = False
# numberBuilt<0 or ntree<0 or numberBuilt>ntree or \
# ntree!=rfView['ntree']
if errorInResponse:
raise Exception("\nBad values in %s.json\n" % whichUsed +
"progress: %s, progressTotal: %s, ntree: %s, numberBuilt: %s, status: %s" % \
(progress, progressTotal, ntree, numberBuilt, status))
if (browseAlso | h2o_args.browse_json):
h2b.browseJsonHistoryAsUrlLastMatch(whichUsed)
return rfView
def set_column_names(self, timeoutSecs=300, print_params=False, **kwargs):
params_dict = {
'copy_from': None,
'source': None,
'cols': None,
'comma_separated_list': None,
}
check_params_update_kwargs(params_dict, kwargs, 'set_column_names', print_params)
a = self.do_json_request('2/SetColumnNames2.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\nset_column_names result:", dump_json(a))
return a
def quantiles(self, timeoutSecs=300, print_params=True, **kwargs):
params_dict = {
'source_key': None,
'column': None,
'quantile': None,
'max_qbins': None,
'interpolation_type': None,
'multiple_pass': None,
}
check_params_update_kwargs(params_dict, kwargs, 'quantiles', print_params)
a = self.do_json_request('2/QuantilesPage.json', timeout=timeoutSecs, params=params_dict)
verboseprint("\nquantiles result:", dump_json(a))
return a
def anomaly(self, timeoutSecs=300, retryDelaySecs=1, initialDelaySecs=5, pollTimeoutSecs=30,
noPoll=False, print_params=True, benchmarkLogging=None, **kwargs):
params_dict = {
'destination_key': None,
'source': None,
'dl_autoencoder_model': None,
'thresh': -1,
}
check_params_update_kwargs(params_dict, kwargs, 'anomaly', print_params)
a = self.do_json_request('2/Anomaly.json', timeout=timeoutSecs, params=params_dict)
if noPoll:
return a
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs, benchmarkLogging=benchmarkLogging,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs)
verboseprint("\nanomaly result:", dump_json(a))
return a
def deep_features(self, timeoutSecs=300, retryDelaySecs=1, initialDelaySecs=5, pollTimeoutSecs=30,
noPoll=False, print_params=True, benchmarkLogging=None, **kwargs):
params_dict = {
'destination_key': None,
'source': None,
'dl_model': None,
'layer': -1,
}
check_params_update_kwargs(params_dict, kwargs, 'deep_features', print_params)
a = self.do_json_request('2/DeepFeatures.json', timeout=timeoutSecs, params=params_dict)
if noPoll:
return a
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs, benchmarkLogging=benchmarkLogging,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs)
verboseprint("\ndeep_features result:", dump_json(a))
return a
def naive_bayes(self, timeoutSecs=300, retryDelaySecs=1, initialDelaySecs=5, pollTimeoutSecs=30,
noPoll=False, print_params=True, benchmarkLogging=None, **kwargs):
params_dict = {
'destination_key': None,
'source': None,
'response': None,
'cols': None,
'ignored_cols': None,
'ignored_cols_by_name': None,
'laplace': None,
'drop_na_cols': None,
'min_std_dev': None,
}
check_params_update_kwargs(params_dict, kwargs, 'naive_bayes', print_params)
a = self.do_json_request('2/NaiveBayes.json', timeout=timeoutSecs, params=params_dict)
if noPoll:
return a
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs, benchmarkLogging=benchmarkLogging,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs)
verboseprint("\nnaive_bayes result:", dump_json(a))
return a
def anomaly(self, timeoutSecs=300, retryDelaySecs=1, initialDelaySecs=5, pollTimeoutSecs=30,
noPoll=False, print_params=True, benchmarkLogging=None, **kwargs):
params_dict = {
'destination_key': None,
'source': None,
'dl_autoencoder_model': None,
'thresh': None,
}
check_params_update_kwargs(params_dict, kwargs, 'anomaly', print_params)
start = time.time()
a = self.do_json_request('2/Anomaly.json', timeout=timeoutSecs, params=params_dict)
if noPoll:
return a
a = self.poll_url(a, timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs, benchmarkLogging=benchmarkLogging,
initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs)
verboseprint("\nanomaly :result:", dump_json(a))
a['python_elapsed'] = time.time() - start
a['python_%timeout'] = a['python_elapsed'] * 100 / timeoutSecs
return a