PyBNesian is a Python package that implements Bayesian networks. PyBNesian allows extending itsfunctionality using Python code, so new research can be easily developed.
Project description
PyBNesian
-
PyBNesian
is a Python package that implements Bayesian networks. Currently, it is mainly dedicated to learning Bayesian networks. -
PyBNesian
is implemented in C++, to achieve significant performance gains. It uses Apache Arrow to enable fast interoperability between Python and C++. In addition, some parts are implemented in OpenCL to achieve GPU acceleration. -
PyBNesian
allows extending its functionality using Python code, so new research can be easily developed.
Implementation
Currently PyBNesian
implements the following features:
Models
-
Bayesian networks.
-
Conditional Bayesian networks (see section 5.6 of [1]).
-
Dynamic Bayesian networks.
which can have different types of CPDs:
-
Multinomial.
-
Linear Gaussian.
-
Conditional kernel density estimation (ratio of two kernel density estimation models). Accelerated with OpenCL.
with this combinations of CPDs, we implement the following types of networks (which can also be Conditional or Dynamic):
-
Discrete networks.
-
Gaussian networks.
-
Semiparametric networks.
-
Hybrid networks (conditional linear Gaussian networks and semiparametric networks).
Graphs
-
DAGs.
-
Directed graphs.
-
Undirected graphs.
-
Partially directed graphs.
Graph classes implement useful functionalities for probabilistic graphical models, such as moving between DAG-PDAG representation or fast access to root and leaves.
Learning
It implements different structure learning algorithms:
-
Greedy hill-climbing (for Bayesian networks and Conditional Bayesian networks).
-
PC-stable (for Bayesian networks and Conditional Bayesian networks).
-
MMPC (for Bayesian networks and Conditional Bayesian networks).
-
MMHC (for Bayesian networks and conditional Bayesian networks).
-
DMMHC (for dynamic Bayesian networks).
The score and search algorithms can be used with the following scores:
-
BIC.
-
BGe.
-
BDe.
-
Cross-validation likelihood.
-
Holdout likelihood.
-
Cross-validated likelihood with validation dataset. This score combines the cross-validation likelihood with a validation dataset to control the overfitting.
and the following the following learning operators:
-
Arc operations: add arc, remove arc, flip arc.
-
Change Node Type (for semiparametric Bayesian networks).
The following independence tests are implemented for the constraint-based algorithms:
-
Chi-square test.
-
partial correlation test t-test.
-
A likelihood-ratio test based on mutual information assuming a Gaussian distribution for the continuous data.
-
CMIknn [2].
-
RCoT [3].
It also implements the parameter learning:
- Maximum Likelihood Estimator.
Inference
Not implemented right now, as the priority is the learning algorithms. However, all the CPDs and models have a sample()
method, which can be used to create easily an approximate inference engine based on sampling.
Serialization
All relevant objects (graphs, CPDs, Bayesian networks, etc) can be saved/loaded using the pickle format.
Other implementations
PyBNesian
exposes the implementation of other models or techniques used within the library.
-
Apply cross-validation to a dataset.
-
Apply holdout to a dataset.
-
Kernel Density Estimation. Accelerated with OpenCL.
-
K-d Tree. (implemented but not exposed yet).
Weighted sums of chi-squared random variables:
-
Hall-Buckley-Eagleson approximation. (implemented but not exposed yet).
-
Lindsay-Pilla-Basak approximation. (implemented but not exposed yet).
Usage example
>>> from pybnesian import GaussianNetwork, LinearGaussianCPD
>>> # Create a GaussianNetwork with 4 nodes and no arcs.
>>> gbn = GaussianNetwork(['a', 'b', 'c', 'd'])
>>> # Create a GaussianNetwork with 4 nodes and 3 arcs.
>>> gbn = GaussianNetwork(['a', 'b', 'c', 'd'], [('a', 'c'), ('b', 'c'), ('c', 'd')])
>>> # Return the nodes of the network.
>>> print("Nodes: " + str(gbn.nodes()))
Nodes: ['a', 'b', 'c', 'd']
>>> # Return the arcs of the network.
>>> print("Arcs: " + str(gbn.nodes()))
Arcs: ['a', 'b', 'c', 'd']
>>> # Return the parents of c.
>>> print("Parents of c: " + str(gbn.parents('c')))
Parents of c: ['b', 'a']
>>> # Return the children of c.
>>> print("Children of c: " + str(gbn.children('c')))
Children of c: ['d']
>>> # You can access to the graph of the network.
>>> graph = gbn.graph()
>>> # Return the roots of the graph.
>>> print("Roots: " + str(sorted(graph.roots())))
Roots: ['a', 'b']
>>> # Return the leaves of the graph.
>>> print("Leaves: " + str(sorted(graph.leaves())))
Leaves: ['d']
>>> # Return the topological sort.
>>> print("Topological sort: " + str(graph.topological_sort()))
Topological sort: ['a', 'b', 'c', 'd']
>>> # Add an arc.
>>> gbn.add_arc('a', 'b')
>>> # Flip (reverse) an arc.
>>> gbn.flip_arc('a', 'b')
>>> # Remove an arc.
>>> gbn.remove_arc('b', 'a')
>>> # We can also add nodes.
>>> gbn.add_node('e')
4
>>> # We can get the number of nodes
>>> assert gbn.num_nodes() == 5
>>> # ... and the number of arcs
>>> assert gbn.num_arcs() == 3
>>> # Remove a node.
>>> gbn.remove_node('b')
>>> # Each node has an unique index to identify it
>>> print("Indices: " + str(gbn.indices()))
Indices: {'e': 4, 'c': 2, 'd': 3, 'a': 0}
>>> idx_a = gbn.index('a')
>>> # And we can get the node name from the index
>>> print("Node 2: " + str(gbn.name(2)))
Node 2: c
>>> # The model is not fitted right now.
>>> assert gbn.fitted() == False
>>> # Create a LinearGaussianCPD (variable, parents, betas, variance)
>>> d_cpd = LinearGaussianCPD("d", ["c"], [3, 1.2], 0.5)
>>> # Add the CPD to the GaussianNetwork
>>> gbn.add_cpds([d_cpd])
>>> # The CPD is still not fitted because there are 3 nodes without CPD.
>>> assert gbn.fitted() == False
>>> # Let's generate some random data to fit the model.
>>> import numpy as np
>>> np.random.seed(1)
>>> import pandas as pd
>>> DATA_SIZE = 100
>>> a_array = np.random.normal(3, np.sqrt(0.5), size=DATA_SIZE)
>>> c_array = -4.2 - 1.2*a_array + np.random.normal(0, np.sqrt(0.75), size=DATA_SIZE)
>>> d_array = 3 + 1.2 * c_array + np.random.normal(0, np.sqrt(0.5), size=DATA_SIZE)
>>> e_array = np.random.normal(0, 1, size=DATA_SIZE)
>>> df = pd.DataFrame({'a': a_array,
... 'c': c_array,
... 'd': d_array,
... 'e': e_array
... })
>>> # Fit the model. You can pass a pandas.DataFrame or a pyarrow.RecordBatch as argument.
>>> # This fits the remaining CPDs
>>> gbn.fit(df)
>>> assert gbn.fitted() == True
>>> # Check the learned CPDs.
>>> print(gbn.cpd('a'))
[LinearGaussianCPD] P(a) = N(3.043, 0.396)
>>> print(gbn.cpd('c'))
[LinearGaussianCPD] P(c | a) = N(-4.423 + -1.083*a, 0.659)
>>> print(gbn.cpd('d'))
[LinearGaussianCPD] P(d | c) = N(3.000 + 1.200*c, 0.500)
>>> print(gbn.cpd('e'))
[LinearGaussianCPD] P(e) = N(-0.020, 1.144)
>>> # You can sample some data
>>> sample = gbn.sample(50)
>>> # Compute the log-likelihood of each instance
>>> ll = gbn.logl(sample)
>>> # or the sum of log-likelihoods.
>>> sll = gbn.slogl(sample)
>>> assert np.isclose(ll.sum(), sll)
>>> # Save the model, include the CPDs in the file.
>>> gbn.save('test', include_cpd=True)
>>> # Load the model
>>> from pybnesian import load
>>> loaded_gbn = load('test.pickle')
>>> # Learn the structure using greedy hill-climbing.
>>> from pybnesian import hc, GaussianNetworkType
>>> # Learn a Gaussian network.
>>> learned = hc(df, bn_type=GaussianNetworkType())
>>> learned.num_arcs()
2
Dependencies
- Python 3.6, 3.7, 3.8 and 3.9.
The library has been tested on Ubuntu 16.04/20.04 and Windows 10, but should be compatible with other operating systems.
Libraries
The library depends on NumPy, Apache Arrow, and pybind11.
Installation
PyBNesian can be installed with pip:
pip install pybnesian
Build from Source
Prerequisites
- Python 3.6, 3.7, 3.8 or 3.9.
- C++17 compatible compiler.
- CMake (it is needed to compile NLopt).
- OpenCL 1.2 headers/library available.
If needed you can select a C++ compiler by setting the environment variable CC
. For example, in Ubuntu, we can use
Clang 11 with the following command before installing PyBNesian:
export CC=clang-11
Building
Clone the repository:
git clone https://github.com/davenza/PyBNesian.git
cd PyBNesian
git checkout v0.1.0 # You can checkout a specific version if you want
python setup.py install
Testing
The library contains tests that can be executed using pytest
. They also require scipy
and pandas
installed.
pip install pytest scipy pandas
Run the tests with:
pytest
References
[1] D. Koller and N. Friedman, Probabilistic Graphical Models: Principles and Techniques, The MIT Press, 2009.
[2] J. Runge, Conditional independence testing based on a nearest-neighbor estimator of conditional mutual information. International Conference on Artificial Intelligence and Statistics, AISTATS 2018, 84, 2018, pp. 938–947.
[3] E. V. Strobl and K. Zhang and S., Visweswaran. Approximate kernel-based conditional independence tests for fast non-parametric causal discovery. Journal of Causal Inference, 7(1), 2019, pp 1-24.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Hashes for pybnesian-0.4.3-cp310-cp310-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1815153ed9b980e058561bdf5928c7ec42c62fee076fe2b9b8eeb1c2f54b56ec |
|
MD5 | 5baac0f28e93f28ea49095aa42e8feab |
|
BLAKE2b-256 | c30ec16bc8bec5a442046bff14fe909778df6661a533512f1529bdd4d2418928 |
Hashes for pybnesian-0.4.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 13afd64e7665f57ea7ed4efc276c5e5472d3542b9f8516ae01e57e1a247bf23e |
|
MD5 | f940e9bb73d3ffcbec4adbced8a7d557 |
|
BLAKE2b-256 | 40056b5b7a445c48c69acfcfa74ce87824b13014eb01844f31f75e75be98fb53 |
Hashes for pybnesian-0.4.3-cp310-cp310-macosx_10_15_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2b8e7fa56c06b2d0d9512477aa3f5f8a21f5439009ef5e0a97ff136ab8a4df71 |
|
MD5 | 516cd629e99a875164f000deb45c4c59 |
|
BLAKE2b-256 | eec3ffb81a608e969cdd5de1760d3b05845f57a00611e6e42bb5ab4faac46c3f |
Hashes for pybnesian-0.4.3-cp39-cp39-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8c4d3a85deed0e84e99e0da48d0bcbd924e3407d536a0b155256186b21ce5608 |
|
MD5 | 9bf04ee2fb08b2b3758f978413260077 |
|
BLAKE2b-256 | d22c8d1a089a15417101a2105bebed673cc42714a96334f5558f8603b518ee34 |
Hashes for pybnesian-0.4.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 653e2956d2ed5356e93dc1d09ed554fe778b56b63d012497525d08619d75fa0d |
|
MD5 | d1cdf571fd7bd29210d1977e81c25ce3 |
|
BLAKE2b-256 | 77e48af234af20042eb2d809bb986d02d02d7463bf434395995839b90b38fa65 |
Hashes for pybnesian-0.4.3-cp39-cp39-macosx_10_15_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f96397c385d065ab3f93d6805af4fb6aec641a3bcc71666b44f2155dd506dcf8 |
|
MD5 | 7010f4d7490f5aa54cc89f9860e8a6a0 |
|
BLAKE2b-256 | bea87e70377827a7fe41accd82f45c99a2fa34309d3904f8a3b544ae633b82a7 |
Hashes for pybnesian-0.4.3-cp38-cp38-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c29425d38b5cfa93c1e4d2e0878f641c6f19d3f258666fff47dd89e93723f576 |
|
MD5 | 696b94936b9d711ce04ba0cc43bd6fe7 |
|
BLAKE2b-256 | 167265dc7b62b249fb3919b3d6f32460edc9672bd8fbc616e825b2e56fe82f02 |
Hashes for pybnesian-0.4.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c177a4fba462eb28af2671663f00829ffe0fec3bbf47a9f671224556b2def712 |
|
MD5 | 0d4639bf07a84dcf2796e392342bd7bf |
|
BLAKE2b-256 | 5bde50fc6b1dff7ca4c67127cd68d76f480b97b9abfb6ab4e0af13ad9a5402c2 |
Hashes for pybnesian-0.4.3-cp38-cp38-macosx_10_15_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1f2fbecd2db8e6606467730abc11f4e88eccca8557b1c908e617d1c9c9e78713 |
|
MD5 | de819065f5e8cb61989fabdcdf87ac91 |
|
BLAKE2b-256 | 8d3ba9fb23e18b934881540fcd0d597b06612dd979fc44783153dc906bdead4c |
Hashes for pybnesian-0.4.3-cp37-cp37m-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 647d0c4065dc053003a4294bf24f95f6485f4b4457ec54966a1f115d288f80be |
|
MD5 | a6f787f3bf506e99f901b532a57e626d |
|
BLAKE2b-256 | e9261026a9b5f1847cf6e74db636908ff74d5e831a745b3d3d461222a89380ce |
Hashes for pybnesian-0.4.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 766231c460e5d7dbee2cc7adf4670d0e79aa006ae208856c901e5becb287af33 |
|
MD5 | 1bf5455c5d256156a7b7a310e3a44c25 |
|
BLAKE2b-256 | d287d7e63a169ad02308266ebc5cf07065c47bf4b4674fb741b81bb6923260fe |
Hashes for pybnesian-0.4.3-cp37-cp37m-macosx_10_15_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fc05d84cc196a05e9b6c9c9dd16c7260442621bdccd873cb4864043d7c5a1580 |
|
MD5 | 235c81f62efb5ff0ad83e3ae74dc9eef |
|
BLAKE2b-256 | d7936fb775ec8d19c75c9ed0ae8e823a796ef8345a9c9689cc208ba8b946c4de |