aboutsummaryrefslogtreecommitdiff
path: root/beliefs/factors/bernoulli_or_cpd.py
diff options
context:
space:
mode:
authorCathy Yeh <cathy@driver.xyz>2017-12-03 20:38:28 -0800
committerCathy Yeh <cathy@driver.xyz>2017-12-03 20:38:28 -0800
commit26b43410569044aff46053cae7c68862825dd4ec (patch)
treeb184df84d416e2ddf837b25baadff4f9feaaa250 /beliefs/factors/bernoulli_or_cpd.py
parent6a1b35f5bf122232d058ed0f3ea19c15629c0cbc (diff)
parentc906bd37fba63ba706cc3b7802bfb18ffb05ee9a (diff)
downloadbeliefs-26b43410569044aff46053cae7c68862825dd4ec.tar.gz
beliefs-26b43410569044aff46053cae7c68862825dd4ec.tar.bz2
beliefs-26b43410569044aff46053cae7c68862825dd4ec.zip
LGS-164 belief propagation for polytrees, special case of OR cpds, refactored from LGSv0.0.2
Diffstat (limited to 'beliefs/factors/bernoulli_or_cpd.py')
-rw-r--r--beliefs/factors/bernoulli_or_cpd.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/beliefs/factors/bernoulli_or_cpd.py b/beliefs/factors/bernoulli_or_cpd.py
new file mode 100644
index 0000000..bfb3a95
--- /dev/null
+++ b/beliefs/factors/bernoulli_or_cpd.py
@@ -0,0 +1,42 @@
+import numpy as np
+
+from beliefs.factors.cpd import TabularCPD
+
+
+class BernoulliOrCPD(TabularCPD):
+ """CPD class for a Bernoulli random variable whose relationship to its
+ parents (also Bernoulli random variables) is described by OR logic.
+
+ If at least one of the variable's parents is True, then the variable
+ is True, and False otherwise.
+ """
+ def __init__(self, variable, parents=[]):
+ """
+ Args:
+ variable: int or string
+ parents: optional, list of int and/or strings
+ """
+ super().__init__(variable=variable,
+ variable_card=2,
+ parents=parents,
+ parents_card=[2]*len(parents),
+ values=[])
+ self._values = []
+
+ @property
+ def values(self):
+ if not any(self._values):
+ self._values = self._build_kwise_values_array(len(self.variables))
+ self._values = self._values.reshape(self.cardinality)
+ return self._values
+
+ @staticmethod
+ def _build_kwise_values_array(k):
+ # special case a completely independent factor, and
+ # return the uniform prior
+ if k == 1:
+ return np.array([0.5, 0.5])
+
+ return np.array(
+ [1.,] + [0.]*(2**(k-1)-1) + [0.,] + [1.]*(2**(k-1)-1)
+ )