Skip to main content

Python package for learning the graphical structure of Bayesian networks, parameter learning, inference and sampling methods.

Project description

bnlearn - Library for Bayesian network learning and inference

Python PyPI Version GitHub Repo stars License Forks Open Issues Project Status Downloads Downloads DOI Docs Medium GitHub repo size Donate Colab

bnlearn is Python package for learning the graphical structure of Bayesian networks, parameter learning, inference and sampling methods. Because probabilistic graphical models can be difficult in usage, Bnlearn for python (this package) is build on the pgmpy package and contains the most-wanted pipelines. Navigate to API documentations for more detailed information.

⭐️ Star this repo if you like it ⭐️

Read the Medium blog for more details.

Documentation pages

On the documentation pages you can find detailed information about the working of the bnlearn with many examples.


It is advisable to create a new environment (e.g. with Conda).
conda create -n env_bnlearn python=3.10
conda activate env_bnlearn
Install bnlearn from PyPI
pip install bnlearn
Install bnlearn from github source
pip install git+
The following functions are available after installation:
# Import library
import bnlearn as bn

# Structure learning

# Compute edge strength with the test statistic
bn.independence_test(model, df, test='chi_square', prune=True)

# Parameter learning

# Inference

# Make predictions

# Based on a DAG, you can sample the number of samples you want.

# Load well known examples to play arround with or load your own .bif file.

# Load simple dataframe of sprinkler dataset.

# Compare 2 graphs

# Plot graph

# To make the directed grapyh undirected

# Convert to one-hot datamatrix

# Derive the topological ordering of the (entire) graph 

# See below for the exact working of the functions
The following methods are also included:
  • inference
  • sampling
  • comparing two networks
  • loading bif files
  • conversion of directed to undirected graphs

Method overview

Learning a Bayesian network can be split into the underneath problems which are all implemented in this package for both discrete, continous and mixed data sets:

  • Structure learning: Given the data: Estimate a DAG that captures the dependencies between the variables.

    • There are multiple manners to perform structure learning.
      • Exhaustivesearch
      • Hillclimbsearch
      • NaiveBayes
      • TreeSearch
        • Chow-liu
        • Tree-augmented Naive Bayes (TAN)
  • Parameter learning: Given the data and DAG: Estimate the (conditional) probability distributions of the individual variables.

  • Inference: Given the learned model: Determine the exact probability values for your queries.


A structured overview of all examples are now available on the documentation pages.

Structure learning
Parameter learning
Complete examples

Various basic examples

    import bnlearn as bn
    # Example dataframe sprinkler_data.csv can be loaded with: 
    df = bn.import_example()
    # df = pd.read_csv('sprinkler_data.csv')
df looks like this
Cloudy  Sprinkler  Rain  Wet_Grass
0         0          1     0          1
1         1          1     1          1
2         1          0     1          1
3         0          0     1          1
4         1          0     1          1
..      ...        ...   ...        ...
995       0          0     0          0
996       1          0     0          0
997       0          0     1          0
998       1          1     0          1
999       1          0     1          1
    model =
    # Compute edge strength with the chi_square test statistic
    model = bn.independence_test(model, df)
    G = bn.plot(model)

  • Choosing various methodtypes and scoringtypes:
    model_hc_bic  =, methodtype='hc', scoretype='bic')
    model_hc_k2   =, methodtype='hc', scoretype='k2')
    model_hc_bdeu =, methodtype='hc', scoretype='bdeu')
    model_ex_bic  =, methodtype='ex', scoretype='bic')
    model_ex_k2   =, methodtype='ex', scoretype='k2')
    model_ex_bdeu =, methodtype='ex', scoretype='bdeu')
    model_cl      =, methodtype='cl', root_node='Wet_Grass')
    model_tan     =, methodtype='tan', root_node='Wet_Grass', class_node='Rain')

Example: Parameter Learning

    import bnlearn as bn
    # Import dataframe
    df = bn.import_example()
    # As an example we set the CPD at False which returns an "empty" DAG
    model = bn.import_DAG('sprinkler', CPD=False)
    # Now we learn the parameters of the DAG using the df
    model_update =, df)
    # Make plot
    G = bn.plot(model_update)

Example: Inference

    import bnlearn as bn
    model = bn.import_DAG('sprinkler')
    query =, variables=['Rain'], evidence={'Cloudy':1,'Sprinkler':0, 'Wet_Grass':1})
    # Lets try another inference
    query =, variables=['Rain'], evidence={'Cloudy':1})



Setting up and maintaining bnlearn has been possible thanks to users and contributors. Thanks to:


Please cite bnlearn in your publications if this is useful for your research. See column right for citation information.


  • Erdogan Taskesen, github: erdogant
  • Contributions are welcome.
  • If you wish to buy me a Coffee for this work, it is very appreciated :)

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bnlearn-0.8.8.tar.gz (67.4 kB view hashes)

Uploaded Source

Built Distribution

bnlearn-0.8.8-py3-none-any.whl (70.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page