-
Notifications
You must be signed in to change notification settings - Fork 33
/
estimators.py
1408 lines (1223 loc) · 53.8 KB
/
estimators.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
"""A suite of cardinality estimators.
In practicular, inference algorithms for autoregressive density estimators can
be found in 'ProgressiveSampling'.
"""
import bisect
import collections
import json
import operator
import time
import numpy as np
import pandas as pd
import torch
import common
import made
import transformer
OPS = {
'>': np.greater,
'<': np.less,
'>=': np.greater_equal,
'<=': np.less_equal,
'=': np.equal
}
class CardEst(object):
"""Base class for a cardinality estimator."""
def __init__(self):
self.query_starts = []
self.query_dur_ms = []
self.errs = []
self.est_cards = []
self.true_cards = []
self.name = 'CardEst'
def Query(self, columns, operators, vals):
"""Estimates cardinality with the specified conditions.
Args:
columns: list of Column objects to filter on.
operators: list of string representing what operation to perform on
respective columns; e.g., ['<', '>='].
vals: list of raw values to filter columns on; e.g., [50, 100000].
These are not bin IDs.
Returns:
Predicted cardinality.
"""
raise NotImplementedError
def OnStart(self):
self.query_starts.append(time.time())
def OnEnd(self):
self.query_dur_ms.append((time.time() - self.query_starts[-1]) * 1e3)
def AddError(self, err):
self.errs.append(err)
def AddError(self, err, est_card, true_card):
self.errs.append(err)
self.est_cards.append(est_card)
self.true_cards.append(true_card)
def __str__(self):
return self.name
def get_stats(self):
return [
self.query_starts, self.query_dur_ms, self.errs, self.est_cards,
self.true_cards
]
def merge_stats(self, state):
self.query_starts.extend(state[0])
self.query_dur_ms.extend(state[1])
self.errs.extend(state[2])
self.est_cards.extend(state[3])
self.true_cards.extend(state[4])
def report(self):
est = self
print(est.name, "max", np.max(est.errs), "99th",
np.quantile(est.errs, 0.99), "95th", np.quantile(est.errs, 0.95),
"median", np.quantile(est.errs, 0.5), "time_ms",
np.mean(est.query_dur_ms))
def QueryToPredicate(columns, operators, vals, wrap_as_string_cols=None):
"""Converts from (c,o,v) to sql string (for Postgres)."""
v_s = [
str(v).replace('T', ' ') if type(v) is np.datetime64 else v
for v in vals
]
v_s = ["\'" + v + "\'" if type(v) is str else str(v) for v in v_s]
if wrap_as_string_cols is not None:
for i in range(len(columns)):
if columns[i].name in wrap_as_string_cols:
v_s[i] = "'" + str(v_s[i]) + "'"
preds = [
c.pg_name + ' ' + o + ' ' + v
for c, o, v in zip(columns, operators, v_s)
]
s = ' and '.join(preds)
return ' where ' + s
def FillInUnqueriedColumns(table, columns, operators, vals):
"""Allows for some columns to be unqueried (i.e., wildcard).
Returns cols, ops, vals, where all 3 lists of all size len(table.columns),
in the table's natural column order.
A None in ops/vals means that column slot is unqueried.
"""
ncols = len(table.columns)
cs = table.columns
os, vs = [None] * ncols, [None] * ncols
for c, o, v in zip(columns, operators, vals):
idx = table.ColumnIndex(c.name)
os[idx] = o
vs[idx] = v
return cs, os, vs
class ProgressiveSampling(CardEst):
"""Progressive sampling."""
def __init__(
self,
model,
table,
r,
device=None,
seed=False,
cardinality=None,
shortcircuit=False # Skip sampling on wildcards?
):
super(ProgressiveSampling, self).__init__()
torch.set_grad_enabled(False)
self.model = model
self.table = table
self.shortcircuit = shortcircuit
if r <= 1.0:
self.r = r # Reduction ratio.
self.num_samples = None
else:
self.num_samples = r
self.seed = seed
self.device = device
self.cardinality = cardinality
if cardinality is None:
self.cardinality = table.cardinality
with torch.no_grad():
self.init_logits = self.model(
torch.zeros(1, self.model.nin, device=device))
self.dom_sizes = [c.DistributionSize() for c in self.table.columns]
self.dom_sizes = np.cumsum(self.dom_sizes)
# Inference optimizations below.
self.traced_fwd = None
# We can't seem to trace this because it depends on a scalar input.
self.traced_encode_input = model.EncodeInput
if 'MADE' in str(model):
for layer in model.net:
if type(layer) == made.MaskedLinear:
if layer.masked_weight is None:
layer.masked_weight = layer.mask * layer.weight
print('Setting masked_weight in MADE, do not retrain!')
for p in model.parameters():
p.detach_()
p.requires_grad = False
self.init_logits.detach_()
with torch.no_grad():
self.kZeros = torch.zeros(self.num_samples,
self.model.nin,
device=self.device)
self.inp = self.traced_encode_input(self.kZeros)
# For transformer, need to flatten [num cols, d_model].
self.inp = self.inp.view(self.num_samples, -1)
def __str__(self):
if self.num_samples:
n = self.num_samples
else:
n = int(self.r * self.table.columns[0].DistributionSize())
return 'psample_{}'.format(n)
def _sample_n(self,
num_samples,
ordering,
columns,
operators,
vals,
inp=None):
ncols = len(columns)
logits = self.init_logits
if inp is None:
inp = self.inp[:num_samples]
masked_probs = []
# Use the query to filter each column's domain.
valid_i_list = [None] * ncols # None means all valid.
for i in range(ncols):
natural_idx = ordering[i]
# Column i.
op = operators[natural_idx]
if op is not None:
# There exists a filter.
valid_i = OPS[op](columns[natural_idx].all_distinct_values,
vals[natural_idx]).astype(np.float32,
copy=False)
else:
continue
# This line triggers a host -> gpu copy, showing up as a
# hotspot in cprofile.
valid_i_list[i] = torch.as_tensor(valid_i, device=self.device)
# Fill in wildcards, if enabled.
if self.shortcircuit:
for i in range(ncols):
natural_idx = i if ordering is None else ordering[i]
if operators[natural_idx] is None and natural_idx != ncols - 1:
if natural_idx == 0:
self.model.EncodeInput(
None,
natural_col=0,
out=inp[:, :self.model.
input_bins_encoded_cumsum[0]])
else:
l = self.model.input_bins_encoded_cumsum[natural_idx -
1]
r = self.model.input_bins_encoded_cumsum[natural_idx]
self.model.EncodeInput(None,
natural_col=natural_idx,
out=inp[:, l:r])
# Actual progressive sampling. Repeat:
# Sample next var from curr logits -> fill in next var
# Forward pass -> curr logits
for i in range(ncols):
natural_idx = i if ordering is None else ordering[i]
# If wildcard enabled, 'logits' wasn't assigned last iter.
if not self.shortcircuit or operators[natural_idx] is not None:
probs_i = torch.softmax(
self.model.logits_for_col(natural_idx, logits), 1)
valid_i = valid_i_list[i]
if valid_i is not None:
probs_i *= valid_i
probs_i_summed = probs_i.sum(1)
masked_probs.append(probs_i_summed)
# If some paths have vanished (~0 prob), assign some nonzero
# mass to the whole row so that multinomial() doesn't complain.
paths_vanished = (probs_i_summed <= 0).view(-1, 1)
probs_i = probs_i.masked_fill_(paths_vanished, 1.0)
if i < ncols - 1:
# Num samples to draw for column i.
if i != 0:
num_i = 1
else:
num_i = num_samples if num_samples else int(
self.r * self.dom_sizes[natural_idx])
if self.shortcircuit and operators[natural_idx] is None:
data_to_encode = None
else:
samples_i = torch.multinomial(
probs_i, num_samples=num_i,
replacement=True) # [bs, num_i]
data_to_encode = samples_i.view(-1, 1)
# Encode input: i.e., put sampled vars into input buffer.
if data_to_encode is not None: # Wildcards are encoded already.
if not isinstance(self.model, transformer.Transformer):
if natural_idx == 0:
self.model.EncodeInput(
data_to_encode,
natural_col=0,
out=inp[:, :self.model.
input_bins_encoded_cumsum[0]])
else:
l = self.model.input_bins_encoded_cumsum[natural_idx
- 1]
r = self.model.input_bins_encoded_cumsum[
natural_idx]
self.model.EncodeInput(data_to_encode,
natural_col=natural_idx,
out=inp[:, l:r])
else:
# Transformer. Need special treatment due to
# right-shift.
l = (natural_idx + 1) * self.model.d_model
r = l + self.model.d_model
if i == 0:
# Let's also add E_pos=0 to SOS (if enabled).
# This is a no-op if disabled pos embs.
self.model.EncodeInput(
data_to_encode, # Will ignore.
natural_col=-1, # Signals SOS.
out=inp[:, :self.model.d_model])
if transformer.MASK_SCHEME == 1:
# Should encode natural_col \in [0, ncols).
self.model.EncodeInput(data_to_encode,
natural_col=natural_idx,
out=inp[:, l:r])
elif natural_idx < self.model.nin - 1:
# If scheme is 0, should not encode the last
# variable.
self.model.EncodeInput(data_to_encode,
natural_col=natural_idx,
out=inp[:, l:r])
# Actual forward pass.
next_natural_idx = i + 1 if ordering is None else ordering[i +
1]
if self.shortcircuit and operators[next_natural_idx] is None:
# If next variable in line is wildcard, then don't do
# this forward pass. Var 'logits' won't be accessed.
continue
if hasattr(self.model, 'do_forward'):
# With a specific ordering.
logits = self.model.do_forward(inp, ordering)
else:
if self.traced_fwd is not None:
logits = self.traced_fwd(inp)
else:
logits = self.model.forward_with_encoded_input(inp)
# Doing this convoluted scheme because m_p[0] is a scalar, and
# we want the corret shape to broadcast.
p = masked_probs[1]
for ls in masked_probs[2:]:
p *= ls
p *= masked_probs[0]
return p.mean().item()
def Query(self, columns, operators, vals):
# Massages queries into natural order.
columns, operators, vals = FillInUnqueriedColumns(
self.table, columns, operators, vals)
# TODO: we can move these attributes to ctor.
ordering = None
if hasattr(self.model, 'orderings'):
ordering = self.model.orderings[0]
orderings = self.model.orderings
elif hasattr(self.model, 'm'):
# MADE.
ordering = self.model.m[-1]
orderings = [self.model.m[-1]]
else:
print('****Warning: defaulting to natural order')
ordering = np.arange(len(columns))
orderings = [ordering]
num_orderings = len(orderings)
# order idx (first/second/... to be sample) -> x_{natural_idx}.
inv_ordering = [None] * len(columns)
for natural_idx in range(len(columns)):
inv_ordering[ordering[natural_idx]] = natural_idx
with torch.no_grad():
inp_buf = self.inp.zero_()
# Fast (?) path.
if num_orderings == 1:
ordering = orderings[0]
self.OnStart()
p = self._sample_n(
self.num_samples,
ordering if isinstance(
self.model, transformer.Transformer) else inv_ordering,
columns,
operators,
vals,
inp=inp_buf)
self.OnEnd()
return np.ceil(p * self.cardinality).astype(dtype=np.int32,
copy=False)
# Num orderings > 1.
ps = []
self.OnStart()
for ordering in orderings:
p_scalar = self._sample_n(self.num_samples // num_orderings,
ordering, columns, operators, vals)
ps.append(p_scalar)
self.OnEnd()
return np.ceil(np.mean(ps) * self.cardinality).astype(
dtype=np.int32, copy=False)
class SampleFromModel(CardEst):
"""Sample from an autoregressive model."""
def __init__(self, model, table, num_samples_per_query, device=None):
super(SampleFromModel, self).__init__()
self.model = model
self.table = table # The table that MADE is trained on.
self.num_samples_per_query = num_samples_per_query
self.device = device #device to use for pytorch
doms = [c.DistributionSize() for c in table.columns]
# Right shift by 1; put 0 at head.
doms[1:] = doms[:-1]
doms[0] = 0
self.cumsum_shifted_doms = np.cumsum(doms)
print('shifted cumsum', self.cumsum_shifted_doms)
def __str__(self):
return 'msample_{}'.format(self.num_samples_per_query)
def SampleTuples(self, num):
"""Samples num tuples from the MADE model"""
samples = self.model.sample(num,
self.device).to(torch.int32).cpu().numpy()
return samples
def Query(self, columns, operators, vals):
columns, operators, vals = FillInUnqueriedColumns(
self.table, columns, operators, vals)
self.OnStart()
# [N, num cols].
tuples = self.SampleTuples(self.num_samples_per_query)
# all_valids:
# [ (col1) T, F, F, T; (col2) F, F, T; (col3) T ]
#
# Samples:
# [ [ 0, 2, 0 ]; [1, 1, 0] ]
#
# Then only the first sample satisfies the query.
all_valids = []
for col, op, val in zip(columns, operators, vals):
if op is not None:
valid = OPS[op](col.all_distinct_values, val)
else:
valid = [True] * col.DistributionSize()
all_valids.extend(valid)
all_valids = np.asarray(all_valids)
# all() along column dimension: indicates whether each sample passes.
s = all_valids.take(tuples + self.cumsum_shifted_doms).all(1).sum()
sel = s * 1.0 / self.num_samples_per_query
self.OnEnd()
return np.ceil(sel * self.table.cardinality).astype(dtype=np.int32)
class Heuristic(CardEst):
"""Uses independence assumption."""
def __init__(self, table):
super(Heuristic, self).__init__()
self.table = table
self.size = self.table.cardinality
def __str__(self):
return 'heuristic'
def Query(self, columns, operators, vals):
self.OnStart()
sels = [
OPS[o](c.data if isinstance(c.data, np.ndarray) else c.data.values,
v).sum() / self.size
for c, o, v in zip(columns, operators, vals)
]
sel = np.prod(sels)
self.OnEnd()
return np.ceil(sel * self.size).astype(np.int32)
class Oracle(CardEst):
"""Returns true cardinalities."""
def __init__(self, table, limit_first_n=None):
super(Oracle, self).__init__()
self.table = table
self.limit_first_n = limit_first_n
def __str__(self):
return 'oracle'
def Query(self, columns, operators, vals, return_masks=False):
assert len(columns) == len(operators) == len(vals)
self.OnStart()
bools = None
for c, o, v in zip(columns, operators, vals):
if self.limit_first_n is None:
inds = OPS[o](c.data, v)
else:
# For data shifts experiment.
inds = OPS[o](c.data[:self.limit_first_n], v)
if bools is None:
bools = inds
else:
bools &= inds
c = bools.sum()
self.OnEnd()
if return_masks:
return bools
return c
class QueryRegionSize(CardEst):
"""Returns query region size including wildcards."""
def __init__(self, table, count_wildcards=True):
super().__init__()
self.table = table
self.count_wildcards = count_wildcards
def __str__(self):
return 'region_size_{}'.format(self.count_wildcards)
def Query(self, columns, operators, vals, return_masks=False):
columns, operators, vals = FillInUnqueriedColumns(
self.table, columns, operators, vals)
total_size = 1.0
for c, o, v in zip(columns, operators, vals):
if o is None:
if self.count_wildcards:
domain_i_size = len(c.all_distinct_values)
else:
domain_i_size = 1.0
else:
domain_i_size = OPS[o](c.all_distinct_values, v).sum()
total_size *= domain_i_size
return total_size
class Const(CardEst):
"""Returns a constant."""
def __init__(self, const):
super().__init__()
self.const = const
def __str__(self):
return 'Const[{}]'.format(self.const)
def Query(self, columns, operators, vals):
self.OnStart()
c = self.const
self.OnEnd()
return c
class Sampling(CardEst):
"""Keep p% of samples in memory."""
def __init__(self, table, p):
super(Sampling, self).__init__()
self.table = table
self.p = p
self.num_samples = int(p * table.cardinality)
self.size = table.cardinality
# TODO: add seed for repro.
self.tuples = table.data.sample(n=self.num_samples)
self.name = str(self)
def __str__(self):
if self.p * 100 != int(self.p * 100):
return 'sample_{:.1f}%'.format(self.p * 100)
return 'sample_{}%'.format(int(self.p * 100))
def Query(self, columns, operators, vals):
assert len(columns) == len(operators) == len(vals)
self.OnStart()
qualifying_tuples = []
for col, op, val in zip(columns, operators, vals):
qualifying_tuples.append(OPS[op](self.tuples[col.name], val))
s = np.all(qualifying_tuples, axis=0).sum()
sel = s * 1.0 / self.num_samples
self.OnEnd()
return np.ceil(sel * self.table.cardinality).astype(dtype=np.int32)
class Postgres(CardEst):
def __init__(self, database, relation, port=None):
"""Postgres estimator (i.e., EXPLAIN). Must have the PG server live.
E.g.,
def MakeEstimators():
return [Postgres('dmv', 'vehicle_reg', None), ...]
Args:
database: string, the database name.
relation: string, the relation name.
port: int, the port.
"""
import psycopg2
super(Postgres, self).__init__()
self.conn = psycopg2.connect(database=database, port=port)
self.conn.autocommit = True
self.cursor = self.conn.cursor()
self.cursor.execute('analyze ' + relation + ';')
self.conn.commit()
self.database = database
self.relation = relation
def __str__(self):
return 'postgres'
def Query(self, columns, operators, vals):
assert len(columns) == len(operators) == len(vals)
pred = QueryToPredicate(columns, operators, vals)
# Use json so it's easier to parse.
query_s = 'explain(format json) select * from ' + self.relation + pred
# print(query_s)
self.OnStart()
self.cursor.execute(query_s)
res = self.cursor.fetchall()
# print(res)
result = res[0][0][0]['Plan']['Plan Rows']
self.OnEnd()
return result
def QueryByExec(self, columns, operators, vals):
# Runs actual query on postgres and returns true cardinality.
assert len(columns) == len(operators) == len(vals)
pred = QueryToPredicate(columns, operators, vals)
query_s = 'select count(*) from ' + self.relation + pred
self.string = query_s
self.cursor.execute(query_s)
result = self.cursor.fetchone()[0]
return result
def Close(self):
self.cursor.close()
self.conn.close()
class BayesianNetwork(CardEst):
"""Progressive sampling with a pomegranate bayes net."""
def build_discrete_mapping(self, table, discretize, discretize_method):
assert discretize_method in ["equal_size",
"equal_freq"], discretize_method
self.max_val = collections.defaultdict(lambda: None)
if not discretize:
return {}
table = table.copy()
mapping = {}
for col_id in range(len(table[0])):
col = table[:, col_id]
if max(col) > discretize:
if discretize_method == "equal_size":
denom = (max(col) + 1) / discretize
fn = lambda v: np.floor(v / denom)
elif discretize_method == "equal_freq":
per_bin = len(col) // discretize
counts = collections.defaultdict(int)
for x in col:
counts[int(x)] += 1
assignments = {}
i = 0
bin_size = 0
for k, count in sorted(counts.items()):
if bin_size > 0 and bin_size + count >= per_bin:
bin_size = 0
i += 1
assignments[k] = i
self.max_val[col_id] = i
bin_size += count
assignments = np.array(
[assignments[i] for i in range(int(max(col) + 1))])
def capture(assignments):
def fn(v):
return assignments[v.astype(np.int32)]
return fn
fn = capture(assignments)
else:
assert False
mapping[col_id] = fn
return mapping
def apply_discrete_mapping(self, table, discrete_mapping):
table = table.copy()
for col_id in range(len(table[0])):
if col_id in discrete_mapping:
fn = discrete_mapping[col_id]
table[:, col_id] = fn(table[:, col_id])
return table
def apply_discrete_mapping_to_value(self, value, col_id, discrete_mapping):
if col_id not in discrete_mapping:
return value
return discrete_mapping[col_id](value)
def __init__(self,
dataset,
num_samples,
algorithm="greedy",
max_parents=-1,
topological_sampling_order=True,
use_pgm=True,
discretize=None,
discretize_method="equal_size",
root=None):
CardEst.__init__(self)
from pomegranate import BayesianNetwork
self.discretize = discretize
self.discretize_method = discretize_method
self.dataset = dataset
self.original_table = self.dataset.tuples.numpy()
self.algorithm = algorithm
self.topological_sampling_order = topological_sampling_order
self.num_samples = num_samples
self.discrete_mapping = self.build_discrete_mapping(
self.original_table, discretize, discretize_method)
self.discrete_table = self.apply_discrete_mapping(
self.original_table, self.discrete_mapping)
print('calling BayesianNetwork.from_samples...', end='')
t = time.time()
self.model = BayesianNetwork.from_samples(self.discrete_table,
algorithm=self.algorithm,
max_parents=max_parents,
n_jobs=8,
root=root)
print('done, took', time.time() - t, 'secs.')
def size(states):
n = 0
for state in states:
if "distribution" in state:
dist = state["distribution"]
else:
dist = state
if dist["name"] == "DiscreteDistribution":
for p in dist["parameters"]:
n += len(p)
elif dist["name"] == "ConditionalProbabilityTable":
for t in dist["table"]:
n += len(t)
if "parents" in dist:
for parent in dist["parents"]:
n += size(dist["parents"])
else:
assert False, dist["name"]
return n
self.size = 4 * size(json.loads(self.model.to_json())["states"])
# print('json:\n', self.model.to_json())
self.json_size = len(self.model.to_json())
self.use_pgm = use_pgm
# print(self.model.to_json())
if topological_sampling_order:
self.sampling_order = []
while len(self.sampling_order) < len(self.model.structure):
for i, deps in enumerate(self.model.structure):
if i in self.sampling_order:
continue # already ordered
if all(d in self.sampling_order for d in deps):
self.sampling_order.append(i)
print("Building sampling order", self.sampling_order)
else:
self.sampling_order = list(range(len(self.model.structure)))
print("Using sampling order", self.sampling_order, str(self))
if use_pgm:
from pgmpy.models import BayesianModel
data = pd.DataFrame(self.discrete_table.astype(np.int64))
spec = []
orphans = []
for i, parents in enumerate(self.model.structure):
for p in parents:
spec.append((p, i))
if not parents:
orphans.append(i)
print("Model spec", spec)
model = BayesianModel(spec)
for o in orphans:
model.add_node(o)
print('calling pgm.BayesianModel.fit...', end='')
t = time.time()
model.fit(data)
print('done, took', time.time() - t, 'secs.')
self.pgm_model = model
def __str__(self):
return "bn-{}-{}-{}-{}-bytes-{}-{}-{}".format(
self.algorithm,
self.num_samples,
"topo" if self.topological_sampling_order else "nat",
self.size,
# self.json_size,
self.discretize,
self.discretize_method if self.discretize else "na",
"pgmpy" if self.use_pgm else "pomegranate")
def Query(self, columns, operators, vals):
if len(columns) != len(self.dataset.table.columns):
columns, operators, vals = FillInUnqueriedColumns(
self.dataset.table, columns, operators, vals)
self.OnStart()
ncols = len(columns)
nrows = self.discrete_table.shape[0]
assert ncols == self.discrete_table.shape[1], (
ncols, self.discrete_table.shape)
def draw_conditional_pgm(evidence, col_id):
"""PGM version of draw_conditional()"""
if operators[col_id] is None:
op = None
val = None
else:
op = OPS[operators[col_id]]
val = self.apply_discrete_mapping_to_value(
self.dataset.table.val_to_bin_funcs[col_id](vals[col_id]),
col_id, self.discrete_mapping)
if self.discretize:
# avoid some bad cases
if val == 0 and operators[col_id] == "<":
val += 1
elif val == self.max_val[col_id] and operators[
col_id] == ">":
val -= 1
def prob_match(distribution):
if not op:
return 1.
p = 0.
for k, v in enumerate(distribution):
if op(k, val):
p += v
return p
from pgmpy.inference import VariableElimination
model_inference = VariableElimination(self.pgm_model)
xi_distribution = []
for row in evidence:
e = {}
for i, v in enumerate(row):
if v is not None:
e[i] = v
result = model_inference.query(variables=[col_id], evidence=e)
xi_distribution.append(result[col_id].values)
xi_marginal = [prob_match(d) for d in xi_distribution]
filtered_distributions = []
for d in xi_distribution:
keys = []
prob = []
for k, p in enumerate(d):
if not op or op(k, val):
keys.append(k)
prob.append(p)
denominator = sum(prob)
if denominator == 0:
prob = [1. for _ in prob] # doesn't matter
if len(prob) == 0:
prob = [1.]
keys = [0.]
prob = np.array(prob) / sum(prob)
filtered_distributions.append((keys, prob))
xi_samples = [
np.random.choice(k, p=v) for k, v in filtered_distributions
]
return xi_marginal, xi_samples
def draw_conditional(evidence, col_id):
"""Draws a new value x_i for the column, and returns P(x_i|prev).
Arguments:
evidence: shape [BATCH, ncols] with None for unknown cols
col_id: index of the current column, i
Returns:
xi_marginal: P(x_i|x0...x_{i-1}), computed by marginalizing
across the range constraint
match_rows: the subset of rows from filtered_rows that also
satisfy the predicate at column i.
"""
if operators[col_id] is None:
op = None
val = None
else:
op = OPS[operators[col_id]]
val = self.apply_discrete_mapping_to_value(
self.dataset.table.val_to_bin_funcs[col_id](vals[col_id]),
col_id, self.discrete_mapping)
if self.discretize:
# avoid some bad cases
if val == 0 and operators[col_id] == "<":
val += 1
elif val == self.max_val[col_id] and operators[
col_id] == ">":
val -= 1
def prob_match(distribution):
if not op:
return 1.
p = 0.
for k, v in distribution.items():
if op(k, val):
p += v
return p
xi_distribution = self.model.predict_proba(evidence,
max_iterations=1,
n_jobs=-1)
xi_marginal = [
prob_match(d[col_id].parameters[0]) for d in xi_distribution
]
filtered_distributions = []
for d in xi_distribution:
keys = []
prob = []
for k, p in d[col_id].parameters[0].items():
if not op or op(k, val):
keys.append(k)
prob.append(p)
denominator = sum(prob)
if denominator == 0:
prob = [1. for _ in prob] # doesn't matter
if len(prob) == 0:
prob = [1.]
keys = [0.]
prob = np.array(prob) / sum(prob)
filtered_distributions.append((keys, prob))
xi_samples = [
np.random.choice(k, p=v) for k, v in filtered_distributions
]
return xi_marginal, xi_samples
p_estimates = [1. for _ in range(self.num_samples)]
evidence = [[None] * ncols for _ in range(self.num_samples)]
for col_id in self.sampling_order:
if self.use_pgm:
xi_marginal, xi_samples = draw_conditional_pgm(evidence, col_id)
else:
xi_marginal, xi_samples = draw_conditional(evidence, col_id)
for ev_list, xi in zip(evidence, xi_samples):
ev_list[col_id] = xi
for i in range(self.num_samples):
p_estimates[i] *= xi_marginal[i]
self.OnEnd()
return int(np.mean(p_estimates) * nrows)
class MaxDiffHistogram(CardEst):