compiled-knowledge 4.1.0a2__cp312-cp312-win32.whl → 4.1.0a3__cp312-cp312-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of compiled-knowledge might be problematic. Click here for more details.

Files changed (33) hide show
  1. ck/circuit/_circuit_cy.c +1 -1
  2. ck/circuit/_circuit_cy.cp312-win32.pyd +0 -0
  3. ck/circuit_compiler/cython_vm_compiler/_compiler.c +152 -152
  4. ck/circuit_compiler/cython_vm_compiler/_compiler.cp312-win32.pyd +0 -0
  5. ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.c +1 -1
  6. ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.cp312-win32.pyd +0 -0
  7. ck/dataset/cross_table.py +143 -79
  8. ck/dataset/dataset.py +95 -7
  9. ck/dataset/dataset_builder.py +11 -4
  10. ck/dataset/dataset_from_crosstable.py +21 -2
  11. ck/learning/coalesce_cross_tables.py +395 -0
  12. ck/learning/model_from_cross_tables.py +242 -0
  13. ck/learning/parameters.py +117 -0
  14. ck/learning/train_generative_bn.py +198 -0
  15. ck/pgm.py +10 -8
  16. ck/pgm_circuit/marginals_program.py +5 -0
  17. ck/pgm_circuit/wmc_program.py +5 -0
  18. ck/pgm_compiler/support/circuit_table/_circuit_table_cy.c +1 -1
  19. ck/pgm_compiler/support/circuit_table/_circuit_table_cy.cp312-win32.pyd +0 -0
  20. ck/probability/divergence.py +226 -0
  21. ck/probability/probability_space.py +43 -19
  22. ck_demos/dataset/demo_dataset_from_sampler.py +18 -0
  23. ck_demos/learning/__init__.py +0 -0
  24. ck_demos/learning/demo_bayesian_network_from_cross_tables.py +71 -0
  25. ck_demos/learning/demo_simple_learning.py +55 -0
  26. ck_demos/sampling/demo_wmc_direct_sampler.py +2 -2
  27. {compiled_knowledge-4.1.0a2.dist-info → compiled_knowledge-4.1.0a3.dist-info}/METADATA +2 -1
  28. {compiled_knowledge-4.1.0a2.dist-info → compiled_knowledge-4.1.0a3.dist-info}/RECORD +32 -24
  29. ck/learning/train_generative.py +0 -149
  30. /ck/{dataset/cross_table_probabilities.py → probability/cross_table_probability_space.py} +0 -0
  31. {compiled_knowledge-4.1.0a2.dist-info → compiled_knowledge-4.1.0a3.dist-info}/WHEEL +0 -0
  32. {compiled_knowledge-4.1.0a2.dist-info → compiled_knowledge-4.1.0a3.dist-info}/licenses/LICENSE.txt +0 -0
  33. {compiled_knowledge-4.1.0a2.dist-info → compiled_knowledge-4.1.0a3.dist-info}/top_level.txt +0 -0
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  import math
2
4
  from abc import ABC, abstractmethod
3
5
  from itertools import chain
@@ -203,16 +205,19 @@ class ProbabilitySpace(ABC):
203
205
  loop_rvs.append([rv[i] for i in sorted(states)])
204
206
  reduced_space = True
205
207
 
208
+ best_probability = float('-inf')
209
+ best_states = None
210
+
206
211
  # If the random variables we are looping over does not have any conditions
207
212
  # then it is expected to be faster by using computed marginal probabilities.
208
213
  if not reduced_space:
209
214
  prs = self.marginal_distribution(*rvs, condition=condition)
210
- best_probability = float('-inf')
211
- best_states = None
212
215
  for probability, inst in zip(prs, rv_instances(*rvs)):
213
216
  if probability > best_probability:
214
217
  best_probability = probability
215
218
  best_states = inst
219
+ if best_states is None:
220
+ return _NAN, ()
216
221
  return best_probability, best_states
217
222
 
218
223
  else:
@@ -220,8 +225,6 @@ class ProbabilitySpace(ABC):
220
225
  new_conditions = tuple(ind for ind in condition if ind.rv_idx not in rv_indexes)
221
226
 
222
227
  # Loop over the state space of the 'loop' rvs
223
- best_probability = float('-inf')
224
- best_states = None
225
228
  indicators: Tuple[Indicator, ...]
226
229
  for indicators in _combos(loop_rvs):
227
230
  probability = self.wmc(*(indicators + new_conditions))
@@ -229,6 +232,8 @@ class ProbabilitySpace(ABC):
229
232
  best_probability = probability
230
233
  best_states = tuple(ind.state_idx for ind in indicators)
231
234
  condition_probability = self.wmc(*condition)
235
+ if best_states is None:
236
+ return _NAN, ()
232
237
  return best_probability / condition_probability, best_states
233
238
 
234
239
  def correlation(self, indicator1: Indicator, indicator2: Indicator, condition: Condition = ()) -> float:
@@ -245,6 +250,20 @@ class ProbabilitySpace(ABC):
245
250
  """
246
251
  condition = check_condition(condition)
247
252
 
253
+ if indicator1.rv_idx == indicator2.rv_idx:
254
+ # Special case - same random variable
255
+ condition_groups: MapSet[int, Indicator] = _group_indicators(condition)
256
+ rv_idx: int = indicator1.rv_idx
257
+ if indicator1 not in condition_groups.get(rv_idx, (indicator1,)):
258
+ return _NAN
259
+ if indicator1 == indicator2:
260
+ return 1
261
+ else:
262
+ if indicator2 not in condition_groups.get(rv_idx, (indicator2,)):
263
+ return _NAN
264
+ else:
265
+ return 0
266
+
248
267
  p1 = self.probability(indicator1, condition=condition)
249
268
  p2 = self.probability(indicator2, condition=condition)
250
269
  p12 = self._joint_probability(indicator1, indicator2, condition=condition)
@@ -267,12 +286,7 @@ class ProbabilitySpace(ABC):
267
286
  entropy of the given random variable.
268
287
  """
269
288
  condition = check_condition(condition)
270
- e = 0.0
271
- for ind in rv:
272
- p = self.probability(ind, condition=condition)
273
- if p > 0.0:
274
- e -= p * math.log2(p)
275
- return e
289
+ return -sum(plogp(self.probability(ind, condition=condition)) for ind in rv)
276
290
 
277
291
  def conditional_entropy(self, rv1: RandomVariable, rv2: RandomVariable, condition: Condition = ()) -> float:
278
292
  """
@@ -309,13 +323,11 @@ class ProbabilitySpace(ABC):
309
323
  joint entropy of the given random variables.
310
324
  """
311
325
  condition = check_condition(condition)
312
- e = 0.0
313
- for ind1 in rv1:
314
- for ind2 in rv2:
315
- p = self._joint_probability(ind1, ind2, condition=condition)
316
- if p > 0.0:
317
- e -= p * math.log2(p)
318
- return e
326
+ return -sum(
327
+ plogp(self._joint_probability(ind1, ind2, condition=condition))
328
+ for ind1 in rv1
329
+ for ind2 in rv2
330
+ )
319
331
 
320
332
  def mutual_information(self, rv1: RandomVariable, rv2: RandomVariable, condition: Condition = ()) -> float:
321
333
  """
@@ -419,8 +431,12 @@ class ProbabilitySpace(ABC):
419
431
  denominator = self.joint_entropy(rv1, rv2, condition=condition)
420
432
  return self._normalised_mutual_information(rv1, rv2, denominator, condition=condition)
421
433
 
422
- def covariant_normalised_mutual_information(self, rv1: RandomVariable, rv2: RandomVariable,
423
- condition: Condition = ()) -> float:
434
+ def covariant_normalised_mutual_information(
435
+ self,
436
+ rv1: RandomVariable,
437
+ rv2: RandomVariable,
438
+ condition: Condition = (),
439
+ ) -> float:
424
440
  """
425
441
  Calculate the covariant normalised mutual information
426
442
  = I(rv1; rv2) / sqrt(H(rv1) * H(rv2)).
@@ -549,6 +565,14 @@ class ProbabilitySpace(ABC):
549
565
  return wmc
550
566
 
551
567
 
568
+ def plogp(p: float) -> float:
569
+ """
570
+ Returns:
571
+ p * log2(p)
572
+ """
573
+ return p * math.log2(p) if p > 0 else 0
574
+
575
+
552
576
  def check_condition(condition: Condition) -> Tuple[Indicator, ...]:
553
577
  """
554
578
  Make the best effort to interpret the given condition.
@@ -0,0 +1,18 @@
1
+ from ck import example
2
+ from ck.dataset.sampled_dataset import dataset_from_sampler
3
+ from ck.pgm import PGM
4
+ from ck.pgm_circuit.wmc_program import WMCProgram
5
+ from ck.pgm_compiler import DEFAULT_PGM_COMPILER
6
+ from ck.sampling.sampler import Sampler
7
+
8
+
9
+ def main() -> None:
10
+ pgm: PGM = example.Student()
11
+ sampler: Sampler = WMCProgram(DEFAULT_PGM_COMPILER(pgm)).sample_direct()
12
+ dataset = dataset_from_sampler(sampler, 10)
13
+
14
+ dataset.dump()
15
+
16
+
17
+ if __name__ == '__main__':
18
+ main()
File without changes
@@ -0,0 +1,71 @@
1
+ from typing import List, Set
2
+
3
+ from ck import example
4
+ from ck.dataset import HardDataset
5
+ from ck.dataset.cross_table import CrossTable, cross_table_from_hard_dataset
6
+ from ck.dataset.sampled_dataset import dataset_from_sampler
7
+ from ck.learning.model_from_cross_tables import model_from_cross_tables
8
+ from ck.pgm import PGM, RandomVariable
9
+ from ck.pgm_circuit.wmc_program import WMCProgram
10
+ from ck.pgm_compiler import DEFAULT_PGM_COMPILER
11
+ from ck.probability import divergence
12
+
13
+ EXCLUDE_UNNECESSARY_CROSS_TABLES = True
14
+
15
+
16
+ def main() -> None:
17
+ number_of_samples: int = 10000 # How many instances to make for the model dataset
18
+
19
+ # Create a dataset based on model which is an example PGM
20
+ model: PGM = example.Student()
21
+ model_dataset = dataset_from_sampler(
22
+ WMCProgram(DEFAULT_PGM_COMPILER(model)).sample_direct(),
23
+ number_of_samples,
24
+ )
25
+
26
+ # Clone the model, without factors, and transport the dataset to the new PGM
27
+ pgm = PGM()
28
+ dataset = HardDataset(weights=model_dataset.weights)
29
+ for model_rv in model.rvs:
30
+ rv = pgm.new_rv(model_rv.name, model_rv.states)
31
+ dataset.add_rv_from_state_idxs(rv, model_dataset.state_idxs(model_rv))
32
+
33
+ # What model rvs have a child
34
+ model_rvs_with_children: Set[RandomVariable] = set()
35
+ for model_factor in model.factors:
36
+ for parent_rv in model_factor.rvs[1:]:
37
+ model_rvs_with_children.add(parent_rv)
38
+
39
+ # Construct cross-tables from the dataset
40
+ cross_tables: List[CrossTable] = []
41
+ for model_factor in model.factors:
42
+ if (
43
+ EXCLUDE_UNNECESSARY_CROSS_TABLES
44
+ and len(model_factor.rvs) == 1
45
+ and model_factor.rvs[0] in model_rvs_with_children
46
+ ):
47
+ # The factor relates to a single random variable (has
48
+ # no parents) but it does have children.
49
+ # No need to include a cross-table as it is inferable from
50
+ # cross-tables of its children.
51
+ continue
52
+
53
+ rvs = tuple(pgm.rvs[model_rv.idx] for model_rv in model_factor.rvs)
54
+ cross_tables.append(cross_table_from_hard_dataset(dataset, rvs))
55
+ print('cross-table:', *rvs)
56
+
57
+ # Train the PGM
58
+ model_from_cross_tables(pgm, cross_tables)
59
+
60
+ # Show results
61
+ print()
62
+ pgm.dump(show_function_values=True)
63
+ print()
64
+ model_space = WMCProgram(DEFAULT_PGM_COMPILER(model))
65
+ pgm_space = WMCProgram(DEFAULT_PGM_COMPILER(pgm))
66
+ print('HI', divergence.hi(model_space, pgm_space))
67
+ print('KL', divergence.kl(model_space, pgm_space))
68
+
69
+
70
+ if __name__ == '__main__':
71
+ main()
@@ -0,0 +1,55 @@
1
+ from ck.dataset.dataset_from_csv import hard_dataset_from_csv
2
+ from ck.learning.train_generative_bn import train_generative_bn
3
+ from ck.pgm import PGM
4
+
5
+
6
+ def main() -> None:
7
+ pgm = PGM('Student')
8
+
9
+ difficult = pgm.new_rv('difficult', ['y', 'n'])
10
+ intelligent = pgm.new_rv('intelligent', ['y', 'n'])
11
+ grade = pgm.new_rv('grade', ['low', 'medium', 'high'])
12
+ award = pgm.new_rv('award', ['y', 'n'])
13
+ letter = pgm.new_rv('letter', ['y', 'n'])
14
+
15
+ pgm.new_factor(difficult)
16
+ pgm.new_factor(intelligent)
17
+ pgm.new_factor(grade, intelligent, difficult)
18
+ pgm.new_factor(award, intelligent)
19
+ pgm.new_factor(letter, grade)
20
+
21
+ rvs = (difficult, intelligent, grade, award, letter)
22
+ csv = """
23
+ 0,1,2,0,1
24
+ 1,1,2,0,1
25
+ 1,1,2,0,1
26
+ 0,0,2,0,0
27
+ 0,1,1,1,0
28
+ 1,1,1,1,1
29
+ 1,1,0,0,0
30
+ 1,1,0,0,1
31
+ 1,0,0,0,0
32
+ """
33
+
34
+ dataset = hard_dataset_from_csv(rvs, csv.splitlines())
35
+
36
+ # Learn parameters values for `pgm` using the training data `dataset`.
37
+ # This updates the PGMs potential functions.
38
+ train_generative_bn(pgm, dataset)
39
+
40
+ show_pgm_factors(pgm)
41
+
42
+ print('Done.')
43
+
44
+
45
+ def show_pgm_factors(pgm: PGM) -> None:
46
+ for factor in pgm.factors:
47
+ potential_function = factor.function
48
+ print(f'Factor: {factor} {type(potential_function)}')
49
+ for instance, _, param_value in potential_function.keys_with_param:
50
+ print(f'Factor{instance} = {param_value}')
51
+ print()
52
+
53
+
54
+ if __name__ == '__main__':
55
+ main()
@@ -2,7 +2,7 @@ import random
2
2
 
3
3
  from ck import example
4
4
  from ck.pgm import PGM
5
- from ck.pgm_compiler import factor_elimination
5
+ from ck.pgm_compiler import DEFAULT_PGM_COMPILER
6
6
  from ck.pgm_circuit import PGMCircuit
7
7
  from ck.pgm_circuit.wmc_program import WMCProgram
8
8
  from ck.probability.empirical_probability_space import EmpiricalProbabilitySpace
@@ -18,7 +18,7 @@ def main():
18
18
 
19
19
  pgm: PGM = example.Rain()
20
20
 
21
- pgm_cct: PGMCircuit = factor_elimination.compile_pgm(pgm)
21
+ pgm_cct: PGMCircuit = DEFAULT_PGM_COMPILER(pgm)
22
22
  wmc = WMCProgram(pgm_cct)
23
23
  sampler = wmc.sample_direct()
24
24
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: compiled-knowledge
3
- Version: 4.1.0a2
3
+ Version: 4.1.0a3
4
4
  Summary: A Python package for compiling and querying discrete probabilistic graphical models.
5
5
  Author-email: Barry Drake <barry@compiledknowledge.org>
6
6
  License-Expression: MIT
@@ -13,6 +13,7 @@ Description-Content-Type: text/markdown
13
13
  License-File: LICENSE.txt
14
14
  Requires-Dist: llvmlite
15
15
  Requires-Dist: numpy
16
+ Requires-Dist: scipy
16
17
  Dynamic: license-file
17
18
 
18
19
  Compiled Knowledge
@@ -1,8 +1,8 @@
1
1
  ck/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- ck/pgm.py,sha256=DXI3RZWBlk6wNj9VlAEDGeEUQ1WIpQwojVAt231K-Co,121095
2
+ ck/pgm.py,sha256=MaUPE1ymO9hX4Z-b780iX1w-5veU5VeMO5nFfvJ9e8U,121189
3
3
  ck/circuit/__init__.py,sha256=klUR7OVESf53-8Ho4f32clHFsR2SOz4XgwZzfDlms88,418
4
- ck/circuit/_circuit_cy.c,sha256=bEZxHMg02hky24K05HBdsLCHl8n-z6btIx5v-3q6nBE,1741715
5
- ck/circuit/_circuit_cy.cp312-win32.pyd,sha256=yVlwVrATq-xKGydrV8LO4Wg5IMCa9UMcLT0bZSX-tdM,221184
4
+ ck/circuit/_circuit_cy.c,sha256=tNGfcT-8cwUIHwYGB4KOShUONM8ot0Hz-ixeqGPwKI0,1741715
5
+ ck/circuit/_circuit_cy.cp312-win32.pyd,sha256=rXbBlHI73FEVMdMeENcP6KwD1z08em2hIT4Wk_RSDqo,221184
6
6
  ck/circuit/_circuit_cy.pxd,sha256=F1WU4KuX_knXQX-hwNKoHsoUK3fJLbLOxEnomWMJFpI,1057
7
7
  ck/circuit/_circuit_cy.pyx,sha256=TIjqsdyN_IzOm9XQw26kEURpL6GSL1kJO3K-UUlkbQc,27763
8
8
  ck/circuit/_circuit_py.py,sha256=gQZoEphxut2UyBL0ZqmNc8KlNBSMST_VOCqOpDMIRSM,28331
@@ -14,25 +14,24 @@ ck/circuit_compiler/llvm_compiler.py,sha256=6RHUCVWCOgt3ZNyjRTl2Z2npYJMWyAFJVAIc
14
14
  ck/circuit_compiler/llvm_vm_compiler.py,sha256=XJhiAZmGMRRz49XUfng9lgETxVw6NgD6XCI0H3fX-1E,22200
15
15
  ck/circuit_compiler/named_circuit_compilers.py,sha256=snlD3JnhAZC-atKpf5GD0v4CGdvj2_ZhCZ3O-tsxzxc,2284
16
16
  ck/circuit_compiler/cython_vm_compiler/__init__.py,sha256=pEAwTleuZgdYhTAQMea2f9YsFK54eoNbZSbrWkW8aeE,49
17
- ck/circuit_compiler/cython_vm_compiler/_compiler.c,sha256=GREvGu6-cceMpuIht7mHBloWicb2jvTy9d4wjbatX3g,871325
18
- ck/circuit_compiler/cython_vm_compiler/_compiler.cp312-win32.pyd,sha256=ATnbDBWk4dvHNeMzSdd-9r0frnKB3qb1txK1efC_QhI,91648
17
+ ck/circuit_compiler/cython_vm_compiler/_compiler.c,sha256=WypS3fPRAeal8e5qXrhr-yAlehCN7anOp31nxrZahyI,871325
18
+ ck/circuit_compiler/cython_vm_compiler/_compiler.cp312-win32.pyd,sha256=QZSeYopWFzkBAGusscJq9Asr3Lu5zaUTCq-WFxt46GQ,91648
19
19
  ck/circuit_compiler/cython_vm_compiler/_compiler.pyx,sha256=550r0AkOh8ZuuTRy3e6Aq-YqBQ82EKcap8e6f3zlEuM,13278
20
20
  ck/circuit_compiler/cython_vm_compiler/cython_vm_compiler.py,sha256=3Q-HCyA7VWFoXS9gn-k4LXedzqHPvdFNvWHfDcKYv6s,4473
21
21
  ck/circuit_compiler/support/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
22
  ck/circuit_compiler/support/input_vars.py,sha256=x6krN6sW9A-vZTteY4M4on_0vS4ChaaCcmnXcnQ4y0s,4812
23
23
  ck/circuit_compiler/support/llvm_ir_function.py,sha256=07IUmx4bGReDu-BsUhJEWM_onm8NmsHwQzJan1rnAFE,8572
24
24
  ck/circuit_compiler/support/circuit_analyser/__init__.py,sha256=RbyIObAAb-w0Ky4fB198xAfxTh2doquN9ez68SZSZgo,536
25
- ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.c,sha256=Z_i7EFoOaeztsOJK2iuUPJe6BVUGylcIXyn3WCxFBR0,448751
26
- ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.cp312-win32.pyd,sha256=mPghEcc2-BqHKpoc4q0fOIUhn5Ai32gjxekY5IWztL4,47104
25
+ ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.c,sha256=D5KZEt34naEQYjXupohXZrZtipaZf0TEdphHYsCGk4Q,448751
26
+ ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.cp312-win32.pyd,sha256=ICdyNrcTK1S25eQ6UyOWPn79jwmuyK-BO96F1RStKMs,47104
27
27
  ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_cy.pyx,sha256=ctDOHOjnUhdsR_XHBrgchFVTImLhsEUjU3cqkP-GdF8,3331
28
28
  ck/circuit_compiler/support/circuit_analyser/_circuit_analyser_py.py,sha256=eWjc2B946LeSzcGa9PyI4XQvlx_B1KPEiQuM6OOFjjQ,3086
29
29
  ck/dataset/__init__.py,sha256=3vxB-b8LdgtoZ73q28sdPYPUbCbXARH-fNGUZcxIzIo,56
30
- ck/dataset/cross_table.py,sha256=D8Y0WpISouAkMnt0j8bs4Csw_MhxT6h4eUucaQQOkmw,9745
31
- ck/dataset/cross_table_probabilities.py,sha256=U7LlmWUc_Ow6CVEk_6CLK0p2g8GlRpHEGPZFXrV8tmI,1997
32
- ck/dataset/dataset.py,sha256=fGxjEqv9qfdEq8s1ph8B_ptFftpf1wddVgYH8jDNtr0,22746
33
- ck/dataset/dataset_builder.py,sha256=e9fNbvDl1HhM49DxvvBtXWOHpvPPocBsTTzUsCpkR_A,18912
30
+ ck/dataset/cross_table.py,sha256=j0HxWXJp14lOOJyb23T5LHEWziMYyY2UYnqIxdeG7kM,13348
31
+ ck/dataset/dataset.py,sha256=yuX499Ue4V5T4YQJOEsslpGAoFZv-4UpTRk7zDVZ7B0,26213
32
+ ck/dataset/dataset_builder.py,sha256=ZmDYz5xZrqbQLO4aLcESnBxmo838Z8CD0Y0-YrUNoio,19392
34
33
  ck/dataset/dataset_compute.py,sha256=B1BxTJ-JAsNk8l79iDRmJAQ5QwEvWgsI1wepRg4aQCQ,5845
35
- ck/dataset/dataset_from_crosstable.py,sha256=0I4jr4PtfBtniTFBHlAOlcl_ZH0NSD37azkcA2CaWSQ,1323
34
+ ck/dataset/dataset_from_crosstable.py,sha256=bThBqyM4H0kfg4DonguLW1DIdkAQdlQa5nPAciMnMrI,2345
36
35
  ck/dataset/dataset_from_csv.py,sha256=Nn2RzZP_fhag2UaXzv27YEnKSo6oogKEVGEEafQuB6U,5953
37
36
  ck/dataset/sampled_dataset.py,sha256=8PfiTXqraSQ5rXpFUFFMN13jQL1x--_z9g6FYs2VW1U,3357
38
37
  ck/example/__init__.py,sha256=BXVxvTcl3tqgai-xJiGQIaG_ChlpPRdfWg985MQ7dwM,1744
@@ -77,15 +76,18 @@ ck/in_out/render_bugs.py,sha256=6YBhMIq3VRKFS0XqHbaWj6iz1io7O9icW23kukF_Cic,3383
77
76
  ck/in_out/render_net.py,sha256=LpQYAo_tF45vMIcHW1Ir5Zd_Ot69SPAK-e1Tl_6Ygo0,5147
78
77
  ck/in_out/render_pomegranate.py,sha256=gGvXyX9vOoilGIIL3rsMB07gERMU-12XPsttfSb4xLI,5764
79
78
  ck/learning/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
80
- ck/learning/train_generative.py,sha256=ho1RJPQQ_iq652rRnGoqVnZv4bZHVZshMAxcEsoW3h0,5700
79
+ ck/learning/coalesce_cross_tables.py,sha256=lbEnddpiJ7tsUBBkhZD4kAVJnje-yNVUcGnxg6dgBJo,13321
80
+ ck/learning/model_from_cross_tables.py,sha256=WOgC32zu7H1GA4DeHGeHSk3ehdp5r8iPh7onNQl0myE,9325
81
+ ck/learning/parameters.py,sha256=PXLNq45zvlBqonMkQ1Lb-pYlHPnpI3osi2gabbpZMX0,4505
82
+ ck/learning/train_generative_bn.py,sha256=wBk6xfU1EqvamFlMqScrsmmAVJIF0nFkAFiF3AegLJI,8217
81
83
  ck/pgm_circuit/__init__.py,sha256=B0CCjNMnPzrd0YiOEFdK4JzmRCvFIGJi3RJQ5Vg6fqA,37
82
- ck/pgm_circuit/marginals_program.py,sha256=DUvSND3ozQuBCZcmIsgwZ4w_IWCVV7O31Pm4PJ7ZDok,14786
84
+ ck/pgm_circuit/marginals_program.py,sha256=ZrFDOvsv-Hn7G3rbuXJDtRxFdOpI_J9P7dvSkcBsnng,15139
83
85
  ck/pgm_circuit/mpe_program.py,sha256=-8fcb-txUiKo2bPKhApl_GD7U_gREC5SvU_D5sQe9sg,10226
84
86
  ck/pgm_circuit/pgm_circuit.py,sha256=DLjQmaVuAQ0YF6kCi15vDRiydLCJmufeo0hQJndqv2Y,3375
85
87
  ck/pgm_circuit/program_with_slotmap.py,sha256=5iIPVvhGncluMR-dfCIqXGjmzSnxLL-btfy80PI23DE,8025
86
88
  ck/pgm_circuit/slot_map.py,sha256=T4nBweoiivEdBDhYZ6GWpOXqSusRbp3vrSbCTyP1qpI,857
87
89
  ck/pgm_circuit/target_marginals_program.py,sha256=x4YQM-hUQRo2OLxodKJVOAKxqNlxmiDl9nGbbknypkY,3768
88
- ck/pgm_circuit/wmc_program.py,sha256=WtABU74FOCCJuKRCoDL4CyZ4CJXFmt9RSxiNNHsOhRY,12699
90
+ ck/pgm_circuit/wmc_program.py,sha256=ZVGSyTh4pIP0BqITrHeibWmPNE1ntPp2hyR1bjBd9Tg,13052
89
91
  ck/pgm_circuit/support/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
90
92
  ck/pgm_circuit/support/compile_circuit.py,sha256=5UtwaGQHWp8I5aVECXGQjkzKqXBRdO8dRunQNGSNdXo,3203
91
93
  ck/pgm_compiler/__init__.py,sha256=XCK1AWBBB9UYi6kbFnxMFzBL9a25EWfHnz_yn3ZKYuM,112
@@ -102,14 +104,16 @@ ck/pgm_compiler/support/factor_tables.py,sha256=tV9qE2zC8iwEQxTuXE6qiE6lmMpz4-Vc
102
104
  ck/pgm_compiler/support/join_tree.py,sha256=Chkyyo--ChgWEsDqTh8RCxPN7Z1NyvL--GjTC4ONvkY,12897
103
105
  ck/pgm_compiler/support/named_compiler_maker.py,sha256=g2MLnlkWXkISHL6dh23EY53SptTo7-itfuZogSpMdB8,1420
104
106
  ck/pgm_compiler/support/circuit_table/__init__.py,sha256=yJ05NvuNE9j0E_QnjDzHYfLqcHn5TdOleEpG3wSRgXQ,579
105
- ck/pgm_compiler/support/circuit_table/_circuit_table_cy.c,sha256=5TqAN98gLTZ3inQFBc_b6xpJJjjs2RJsbJ3loHHybho,730350
106
- ck/pgm_compiler/support/circuit_table/_circuit_table_cy.cp312-win32.pyd,sha256=ORrARMf9nQD2dnrf95dV4nQYHZz_5JzW6kH5cIHGMOQ,87040
107
+ ck/pgm_compiler/support/circuit_table/_circuit_table_cy.c,sha256=z7YUP7mDKX7wLq08O_rpphaj8C8s2dUAiWAtWRe1d4U,730350
108
+ ck/pgm_compiler/support/circuit_table/_circuit_table_cy.cp312-win32.pyd,sha256=jJPPoCruDzRvcZEoCHjxRVERAt-fE4eZf9vPYToj8Ek,87040
107
109
  ck/pgm_compiler/support/circuit_table/_circuit_table_cy.pyx,sha256=rVO1yxjZmZ6yv5s0zKq4Ji9WYrDuYTZsRG_zeF1_1xE,12015
108
110
  ck/pgm_compiler/support/circuit_table/_circuit_table_py.py,sha256=h6xPYGBSy6XHQBFLPD2D1-V7Kiw9utY68nWrcGRMEg4,11287
109
111
  ck/probability/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
112
+ ck/probability/cross_table_probability_space.py,sha256=U7LlmWUc_Ow6CVEk_6CLK0p2g8GlRpHEGPZFXrV8tmI,1997
113
+ ck/probability/divergence.py,sha256=v6aRxYGXN1pcUXh6HaAS6_h1eb01pD8D2fXbm4RXMEE,8484
110
114
  ck/probability/empirical_probability_space.py,sha256=sO31UIhePRFtkUDN84HT9qhtWsYa0vYaRdXMsttNgTk,2140
111
115
  ck/probability/pgm_probability_space.py,sha256=Slmp0mwDMoVh_86Y8L1QjAQsneazcK2VGQcRW8O2C3M,1267
112
- ck/probability/probability_space.py,sha256=RXNm2gIVcabjbr6WsNebZMKqL8LY32RRaRMGHE2cU6o,26109
116
+ ck/probability/probability_space.py,sha256=C2ECA2_j4asaIstHL5pdSiDYfwdP30ShDn6pfAJi0Lk,26776
113
117
  ck/program/__init__.py,sha256=Ss9-0eqsGxCGloD6liH-0iqBG5Q3vPRF4XCw2hkDJ0M,110
114
118
  ck/program/program.py,sha256=gDJ5Q2kXZuaoHboa9yNTg0tQH9S-Gmw0BRx6PPV28pU,4184
115
119
  ck/program/program_buffer.py,sha256=1fiUcT7sqyr4vu8jXzK3ZsrgURFhWMdm6hr2BeS9ONA,5665
@@ -146,8 +150,12 @@ ck_demos/circuit_compiler/compare_circuit_compilers.py,sha256=IEzwvKt6c8wrmAyd6F
146
150
  ck_demos/circuit_compiler/show_llvm_program.py,sha256=HKUuyLfBjH6ZgD8l4gQWVSBPUh55ZCXjPa7ZEdm5OyU,712
147
151
  ck_demos/dataset/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
148
152
  ck_demos/dataset/demo_dataset_builder.py,sha256=1OycYIr0C_3NCn0SLNoHftjStnRrGk_f0yNlckD6nh4,1024
153
+ ck_demos/dataset/demo_dataset_from_sampler.py,sha256=7hd1vmnIv_q6qC9K6FSGiYm3vA6DSFapz6vItl1MHqQ,503
149
154
  ck_demos/getting_started/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
150
155
  ck_demos/getting_started/simple_demo.py,sha256=AR40OtUVd-CJOxFlsu8_RtGLL2LLnZg506SzrIx7OQA,668
156
+ ck_demos/learning/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
157
+ ck_demos/learning/demo_bayesian_network_from_cross_tables.py,sha256=hnwj8k-4pDKDy16xk_q83S6LQUP6LveyZH9pGxXG97c,2650
158
+ ck_demos/learning/demo_simple_learning.py,sha256=CtFdMKS8HmUWfr5CwXRkPtTI2HlL3Xw1jQdZcE7_j1s,1538
151
159
  ck_demos/pgm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
152
160
  ck_demos/pgm/demo_pgm_dump.py,sha256=egcjSjMDJdyzxWGvHrgdF_g3CFYozLKv4XSXzvSfWbg,248
153
161
  ck_demos/pgm/demo_pgm_dump_stress.py,sha256=L9S3yp0EQM56kWztV4A6XzEqITOGbThImZIU0JofCDg,285
@@ -182,14 +190,14 @@ ck_demos/sampling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU
182
190
  ck_demos/sampling/check_sampler.py,sha256=ZiXYS9CqGCX-Hd7zMKR_2TWZYTbbgF7TIqvYtq1Ofj0,2106
183
191
  ck_demos/sampling/demo_marginal_direct_sampler.py,sha256=RhNunuIUnYI_GXp9m8wzadMrgH9LYrr_Ohh1NApcFDk,1149
184
192
  ck_demos/sampling/demo_uniform_sampler.py,sha256=Z6tX_OYKGLc_w3-kEPK4KEZlJo7F5HOq_tUVppB_VQE,962
185
- ck_demos/sampling/demo_wmc_direct_sampler.py,sha256=c7maxTmZyIijaVdFs2h_KQbK30LvI-oCm2BXSUXVoD8,1113
193
+ ck_demos/sampling/demo_wmc_direct_sampler.py,sha256=MC6I7kPhVxkdLU5ve31u59c-MjwDuSgHUXsjtRqQIqU,1105
186
194
  ck_demos/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
187
195
  ck_demos/utils/compare.py,sha256=Bwjpflevl4nusfA0zp96rInaVKFGuhC5Xv7HzA1Fobk,5088
188
196
  ck_demos/utils/convert_network.py,sha256=TSKj8q7L7J5rhrvwjaDkdYZ0Sg8vV5FRL_vCanX1CQw,1363
189
197
  ck_demos/utils/sample_model.py,sha256=in-Nlv-iuNIu6y9fDuMyo7nzgimBuTAnCWcpnVqvqDQ,8839
190
198
  ck_demos/utils/stop_watch.py,sha256=VzXHRWx0V8vPSD-bLgLlEYkCkR2FA0-KmM_pfKx-Pxo,13205
191
- compiled_knowledge-4.1.0a2.dist-info/licenses/LICENSE.txt,sha256=uMYx7tmroEKNASizbCOwPveMQsD5UErLDC1_SANmNn8,1089
192
- compiled_knowledge-4.1.0a2.dist-info/METADATA,sha256=41mdCLKoTBDANacEu1V3Al9pup0b_6HjQ-DvBO4WUuk,1837
193
- compiled_knowledge-4.1.0a2.dist-info/WHEEL,sha256=LwxTQZ0gyDP_uaeNCLm-ZIktY9hv6x0e22Q-hgFd-po,97
194
- compiled_knowledge-4.1.0a2.dist-info/top_level.txt,sha256=Cf8DAfd2vcnLiA7HlxoduOzV0Q-8surE3kzX8P9qdks,12
195
- compiled_knowledge-4.1.0a2.dist-info/RECORD,,
199
+ compiled_knowledge-4.1.0a3.dist-info/licenses/LICENSE.txt,sha256=uMYx7tmroEKNASizbCOwPveMQsD5UErLDC1_SANmNn8,1089
200
+ compiled_knowledge-4.1.0a3.dist-info/METADATA,sha256=9Rsb1P6zdDr5k2sWZQdLDvhQpmwzTCehDLM1dGimk3I,1859
201
+ compiled_knowledge-4.1.0a3.dist-info/WHEEL,sha256=LwxTQZ0gyDP_uaeNCLm-ZIktY9hv6x0e22Q-hgFd-po,97
202
+ compiled_knowledge-4.1.0a3.dist-info/top_level.txt,sha256=Cf8DAfd2vcnLiA7HlxoduOzV0Q-8surE3kzX8P9qdks,12
203
+ compiled_knowledge-4.1.0a3.dist-info/RECORD,,
@@ -1,149 +0,0 @@
1
- from dataclasses import dataclass
2
- from typing import Dict, Tuple, List
3
-
4
- import numpy as np
5
-
6
- from ck.dataset import SoftDataset, HardDataset
7
- from ck.dataset.cross_table import CrossTable, cross_table_from_dataset
8
- from ck.pgm import PGM, Instance, DensePotentialFunction, Shape, natural_key_idx, SparsePotentialFunction
9
- from ck.utils.iter_extras import multiply
10
- from ck.utils.np_extras import NDArrayFloat64
11
-
12
-
13
- @dataclass
14
- class ParameterValues:
15
- """
16
- A ParameterValues object represents learned parameter values of a PGM.
17
- """
18
- pgm: PGM
19
- """
20
- The PGM that the parameter values pertains to.
21
- """
22
-
23
- cpts: List[Dict[Instance, NDArrayFloat64]]
24
- """
25
- A list of CPTs co-indexed with `pgm.factors`. Each CPT is a dict
26
- mapping from instances of the parent random variables (of the factors)
27
- to the child conditional probability distribution (CPD).
28
- """
29
-
30
- def set_zero(self) -> None:
31
- """
32
- Set the potential function of each PGM factor to zero.
33
- """
34
- for factor in self.pgm.factors:
35
- factor.set_zero()
36
-
37
- def set_cpt(self) -> None:
38
- """
39
- Set the potential function of each PGM factor to a CPTPotentialFunction,
40
- using our parameter values.
41
- """
42
- for factor, cpt in zip(self.pgm.factors, self.cpts):
43
- factor.set_cpt().set(*cpt.items())
44
-
45
- def set_dense(self) -> None:
46
- """
47
- Set the potential function of each PGM factor to a DensePotentialFunction,
48
- using our parameter values.
49
- """
50
- for factor, cpt in zip(self.pgm.factors, self.cpts):
51
- pot_function: DensePotentialFunction = factor.set_dense()
52
- parent_shape: Shape = factor.shape[1:]
53
- child_state: int
54
- value: float
55
- if len(parent_shape) == 0:
56
- cpd: NDArrayFloat64 = cpt[()]
57
- for child_state, value in enumerate(cpd):
58
- pot_function[child_state] = value
59
- else:
60
- parent_space: int = multiply(parent_shape)
61
- parent_states: Instance
62
- cpd: NDArrayFloat64
63
- for parent_states, cpd in cpt.items():
64
- idx: int = natural_key_idx(parent_shape, parent_states)
65
- for value in cpd:
66
- pot_function[idx] = value
67
- idx += parent_space
68
-
69
- def set_sparse(self) -> None:
70
- """
71
- Set the potential function of each PGM factor to a SparsePotentialFunction,
72
- using our parameter values.
73
- """
74
- for factor, cpt in zip(self.pgm.factors, self.cpts):
75
- pot_function: SparsePotentialFunction = factor.set_sparse()
76
- parent_states: Instance
77
- child_state: int
78
- cpd: NDArrayFloat64
79
- value: float
80
- for parent_states, cpd in cpt.items():
81
- for child_state, value in enumerate(cpd):
82
- key = (child_state,) + parent_states
83
- pot_function[key] = value
84
-
85
-
86
- def train_generative_bn(
87
- pgm: PGM,
88
- dataset: HardDataset | SoftDataset,
89
- *,
90
- dirichlet_prior: float = 0,
91
- check_bayesian_network: bool = True,
92
- ) -> ParameterValues:
93
- """
94
- Maximum-likelihood, generative training for a Bayesian network.
95
-
96
- Args:
97
- pgm: the probabilistic graphical model defining the model structure.
98
- Potential function values are ignored and need not be set.
99
- dataset: a dataset of random variable states.
100
- dirichlet_prior: a real number >= 0. See `CrossTable` for an explanation.
101
- check_bayesian_network: if true and not pgm.is_structure_bayesian an exception will be raised.
102
-
103
- Returns:
104
- a ParameterValues object that can be used to update the parameters of the given PGM.
105
-
106
- Raises:
107
- ValueError: if the given PGM does not have a Bayesian network structure, and check_bayesian_network is True.
108
- """
109
- if check_bayesian_network and not pgm.is_structure_bayesian:
110
- raise ValueError('the given PGM is not a Bayesian network')
111
- cpts: List[Dict[Instance, NDArrayFloat64]] = [
112
- cpt_from_crosstab(cross_table_from_dataset(dataset, factor.rvs, dirichlet_prior=dirichlet_prior))
113
- for factor in pgm.factors
114
- ]
115
- return ParameterValues(pgm, cpts)
116
-
117
-
118
- def cpt_from_crosstab(crosstab: CrossTable) -> Dict[Instance, NDArrayFloat64]:
119
- """
120
- Make a conditional probability table (CPT) from a cross-table.
121
-
122
- Args:
123
- crosstab: a CrossTable representing the weight of unique instances.
124
-
125
- Returns:
126
- a mapping from instances of the parent random variables to the child
127
- conditional probability distribution (CPD).
128
-
129
- Assumes:
130
- the first random variable in `crosstab.rvs` is the child random variable.
131
- """
132
- # Number of states for the child random variable.
133
- child_size: int = len(crosstab.rvs[0])
134
-
135
- # Get distribution over child states for seen parent states
136
- parents_weights: Dict[Instance, NDArrayFloat64] = {}
137
- for state, weight in crosstab.items():
138
- parent_state: Tuple[int, ...] = state[1:]
139
- child_state: int = state[0]
140
- parent_weights = parents_weights.get(parent_state)
141
- if parent_weights is None:
142
- parents_weights[parent_state] = parent_weights = np.zeros(child_size, dtype=np.float64)
143
- parent_weights[child_state] += weight
144
-
145
- # Normalise
146
- for parent_state, parent_weights in parents_weights.items():
147
- parent_weights /= parent_weights.sum()
148
-
149
- return parents_weights