-
Notifications
You must be signed in to change notification settings - Fork 259
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/dbn #174
Draft
liam-adams
wants to merge
14
commits into
mckinsey:develop
Choose a base branch
from
liam-adams:feature/dbn
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Feature/dbn #174
Changes from 3 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
6acc09f
add dynamic bayesian network class
liam-adams e1ac8e0
push branch for Issue 121
liam-adams 15e23cb
push tests for dynamic structure model
liam-adams 0c3fd19
fix tests in dynamic structure model
liam-adams 71b2f93
dynotears tests passing
liam-adams 7d495fc
100% test coverage
liam-adams 326f745
fix linting errors
liam-adams 85df54f
refactored coercion functions for linter
liam-adams e34376c
refactor dsn tests for linter
liam-adams acd9dfe
fix linter error
liam-adams 8fcf355
test doc fix
liam-adams 2143e52
add comment
liam-adams 5c8505b
linter fix
liam-adams 6d0b22b
Merge branch 'develop' into feature/dbn
liam-adams File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -33,3 +33,4 @@ | |
__all__ = ["BayesianNetwork"] | ||
|
||
from .network import BayesianNetwork | ||
from .network import DynamicBayesianNetwork |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,7 +43,7 @@ | |
from pgmpy.models import BayesianModel | ||
|
||
from causalnex.estimator.em import EMSingleLatentVariable | ||
from causalnex.structure import StructureModel | ||
from causalnex.structure import StructureModel, DynamicStructureModel | ||
from causalnex.utils.pgmpy_utils import pd_to_tabular_cpd | ||
|
||
|
||
|
@@ -736,3 +736,84 @@ def _predict_probability_from_incomplete_data( | |
probability = probability[cols] | ||
probability.columns = cols | ||
return probability | ||
|
||
|
||
class DynamicBayesianNetwork(BayesianNetwork): | ||
""" | ||
Base class for Dynamic Bayesian Network (DBN), a probabilistic weighted DAG where nodes represent variables, | ||
edges represent the causal relationships between variables. | ||
|
||
``DynamicBayesianNetwork`` stores nodes with their possible states, edges and | ||
conditional probability distributions (CPDs) of each node. | ||
|
||
``DynamicBayesianNetwork`` is built on top of the ``StructureModel``, which is an extension of ``networkx.DiGraph`` | ||
(see :func:`causalnex.structure.structuremodel.StructureModel`). | ||
|
||
In order to define the ``DynamicBayesianNetwork``, users should provide a relevant ``StructureModel``. | ||
Once ``DynamicBayesianNetwork`` is initialised, no changes to the ``StructureModel`` can be made | ||
and CPDs can be learned from the data. | ||
|
||
The learned CPDs can be then used for likelihood estimation and predictions. | ||
|
||
Example: | ||
:: | ||
>>> # Create a Dynamic Bayesian Network with a manually defined DAG. | ||
>>> from causalnex.structure import StructureModel | ||
>>> from causalnex.network import DynamicBayesianNetwork | ||
>>> | ||
>>> sm = StructureModel() | ||
>>> sm.add_edges_from([ | ||
>>> ('rush_hour', 'traffic'), | ||
>>> ('weather', 'traffic') | ||
>>> ]) | ||
>>> dbn = DynamicBayesianNetwork(sm) | ||
>>> # A created ``DynamicBayesianNetwork`` stores nodes and edges defined by the ``StructureModel`` | ||
>>> dbn.nodes | ||
['rush_hour', 'traffic', 'weather'] | ||
>>> | ||
>>> dbn.edges | ||
[('rush_hour', 'traffic'), ('weather', 'traffic')] | ||
>>> # A ``DynamicBayesianNetwork`` doesn't store any CPDs yet | ||
>>> dbn.cpds | ||
>>> {} | ||
>>> | ||
>>> # Learn the nodes' states from the data | ||
>>> import pandas as pd | ||
>>> data = pd.DataFrame({ | ||
>>> 'rush_hour': [True, False, False, False, True, False, True], | ||
>>> 'weather': ['Terrible', 'Good', 'Bad', 'Good', 'Bad', 'Bad', 'Good'], | ||
>>> 'traffic': ['heavy', 'light', 'heavy', 'light', 'heavy', 'heavy', 'heavy'] | ||
>>> }) | ||
>>> dbn = dbn.fit_node_states(data) | ||
>>> dbn.node_states | ||
{'rush_hour': {False, True}, 'weather': {'Bad', 'Good', 'Terrible'}, 'traffic': {'heavy', 'light'}} | ||
>>> # Learn the CPDs from the data | ||
>>> dbn = dbn.fit_cpds(data) | ||
>>> # Use the learned CPDs to make predictions on the unseen data | ||
>>> test_data = pd.DataFrame({ | ||
>>> 'rush_hour': [False, False, True, True], | ||
>>> 'weather': ['Good', 'Bad', 'Good', 'Bad'] | ||
>>> }) | ||
>>> dbn.predict(test_data, "traffic").to_dict() | ||
>>> {'traffic_prediction': {0: 'light', 1: 'heavy', 2: 'heavy', 3: 'heavy'}} | ||
>>> dbn.predict_probability(test_data, "traffic").to_dict() | ||
{'traffic_prediction': {0: 'light', 1: 'heavy', 2: 'heavy', 3: 'heavy'}} | ||
{'traffic_light': {0: 0.75, 1: 0.25, 2: 0.3333333333333333, 3: 0.3333333333333333}, | ||
'traffic_heavy': {0: 0.25, 1: 0.75, 2: 0.6666666666666666, 3: 0.6666666666666666}} | ||
""" | ||
|
||
def __init__(self, structure: DynamicStructureModel): | ||
""" | ||
Create a ``DynamicBayesianNetwork`` with a DAG defined by ``DynamicStructureModel``. | ||
|
||
Args: | ||
structure: a graph representing a causal relationship between variables. | ||
In the structure | ||
- cycles are not allowed; | ||
- multiple (parallel) edges are not allowed; | ||
- isolated nodes and multiple components are not allowed. | ||
|
||
Raises: | ||
ValueError: If the structure is not a connected DAG. | ||
""" | ||
super().__init__(structure) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just wanted to know if you're clear on the changes that will need to come here. If not let's have a PS anytime :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes i think i need a PS here :) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
looks good.
I think the text should be a bit different from the one in the BN class though. It's ok to keep the similar points, but I would rather say that a DBN is a BN with the time domain taken into account, and it does X and Y that a normal BN doesn't do
WDYT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes i think i need a PS here :)