RepositoryJupyter NotebookNLNetherlands
erdogant

erdogant/bnlearn

Python package for Causal Discovery by learning the graphical structure of Bayesian networks. Structure Learning, Parameter Learning, Inferences, Sampling methods.

649stars
62forks
2issues
3views

Featured achievements

The project's latest awards

1
TINIX TRENDING·Topic: causal-networks

#1 Repository of the month

1
TINIX TRENDING·Topic: sampling-methods

#1 Repository of the month

1
TINIX TRENDING·Topic: structure-learning

#1 Repository of the month

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

bnlearn is Python package for causal discovery by learning the graphical structure of Bayesian networks, parameter learning, inference, and sampling methods. Because probabilistic graphical models can be difficult to use, Bnlearn contains the most-wanted pipelines. Navigate to API documentations for more detailed information. ⭐️ Star it if you like it ⭐️


Key Features

FeatureDescriptionMediumGumroad/Podcast
Causal Discovery - Overview and Starters GuideLearn the basics of causal modelling.link---
Structure LearningLearn the model structure from data or with expert knowledge.linkPodcast
Causal PredictionsLearn to make causal predictions.link---
Parameter LearningEstimate model parameters (e.g., conditional probability distributions) from observed data.linkPodcast
Causal InferenceCompute interventional and counterfactual distributions using do-calculus.linkPodcast
Generate Synthetic DataGenerate synthetic data.linkPodcast
Discretize DataDiscretize continuous datasets.------
ComparisonsComparison with other causal libraries.linkPodcast


The following functions are available after installation:

FeatureDescription
Key Pipelines
Structure learningbn.structure_learning.fit()
Parameter learningbn.parameter_learning.fit()
Inferencebn.inference.fit()
Make predictionsbn.predict()
Generate Synthetic Databn.sampling()
Compute Edge Strengthbn.independence_test()
Key Functions
Imputationsbn.knn_imputer()
Discretizingbn.discretize()
Check Model Parametersbn.check_model()
Create DAGbn.make_DAG()
Get Node Propertiesbn.get_node_properties()
Get Edge Propertiesbn.get_edge_properties()
Get Parents From Edgesbn.get_parents()
Generate Default CPT per Nodebn.generate_cpt()
Generate Default CPTs for All Edgesbn.build_cpts_from_structure()
Make Plots
Plottingbn.plot()
Plot Graphvizbn.plot_graphviz()
Compare 2 Networksbn.compare_networks()
Load DAG (bif files)bn.import_DAG()
Load Examplesbn.import_example()
Transformation Functions
Convert DAG to Undirectedbn.to_undirected()
Convert to one-hotbn.df2onehot()
Convert Adjacency Matrix to Vectorbn.adjmat2vec()
Convert Adjacency Matrix to Dictionarybn.adjmat2dict()
Convert Vector to Adjacency Matrixbn.vec2adjmat()
Convert DAG to Adjacency Matrixbn.dag2adjmat()
Convert DataFrame to Onehotbn.df2onehot()
Convert Query to DataFramebn.query2df()
Convert Vector to DataFramebn.vec2df()
Metrics
Compute Topological Orderingbn.topological_sort()
Compute Structure Scoresbn.structure_scores()
General
Save Modelbn.save()
Load Modelbn.load()
Print CPTsbn.print_CPD()

Installation

Install bnlearn from PyPI
pip install bnlearn
Install bnlearn from github source
pip install git+https://github.com/erdogant/bnlearn
Load library
# Import library
import bnlearn as bn

Code 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')

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 = bn.structure_learning.fit(df)
    # Compute edge strength with the chi-square test statistic
    model = bn.independence_test(model, df)
    G = bn.plot(model)


# Example: Structure Learning

    model_hc_bic  = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')
    model_hc_k2   = bn.structure_learning.fit(df, methodtype='hc', scoretype='k2')
    model_hc_bdeu = bn.structure_learning.fit(df, methodtype='hc', scoretype='bdeu')
    model_ex_bic  = bn.structure_learning.fit(df, methodtype='ex', scoretype='bic')
    model_ex_k2   = bn.structure_learning.fit(df, methodtype='ex', scoretype='k2')
    model_ex_bdeu = bn.structure_learning.fit(df, methodtype='ex', scoretype='bdeu')
    model_cl      = bn.structure_learning.fit(df, methodtype='cl', root_node='Wet_Grass')
    model_tan     = bn.structure_learning.fit(df, 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 = bn.parameter_learning.fit(model, df)
    # Make plot
    G = bn.plot(model_update)

# Example: Inference

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


Star history

Star History Chart

Contributors

Thank the contributors!

Maintainer

  • Erdogan Taskesen, github: erdogant
  • Contributions are welcome.
  • Yes! This library is entirely free but it runs on coffee! :) Feel free to support with a Coffee.

Buy me a coffee

Similar Projects

Discover other similar projects and AI models.

RepositoryPython
mckinsey/causalnex

A Python library that helps data scientists to infer causation rather than observing correlation.

2.5k
Aug 31, 2026
RepositoryTypeScript
erikbrinkman/d3-dag

Layout algorithms for visualizing directed acyclic graphs

1.5k
Nov 23, 2026
RepositoryPython
blackjax-devs/blackjax

BlackJAX is a Bayesian Inference library designed for ease of use, speed and modularity.

1.1k
Nov 23, 2026
RepositoryPython
BiomedSciAI/causallib

A Python package for modular causal inference analysis and model evaluations

836
May 26, 2026
RepositoryPython
cdt15/lingam

Python package for causal discovery based on LiNGAM.

513
Nov 28, 2026
RepositoryJavaScript
byteball/obyte-gui-wallet

Unstoppable money https://obyte.org

429
Nov 17, 2026
Repository
msuzen/looper

A resource list for causality in statistics, data science and physics

268
Aug 1, 2026
RepositoryPython
felixleopoldo/benchpress

Scalable open-source software to run, develop, and benchmark causal discovery algorithms

86
Nov 7, 2026
RepositoryPython
realrate/Causing

Causing: CAUsal INterpretation using Graphs

63
Nov 14, 2026