Package: bnlearn
bnlearn - Library for Bayesian network learning and inferencebnlearnis 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 thepgmpypackage and contains the most-wanted pipelines. Navigate toAPI documentationsfor more detailed information.⭐️ Star this repo if you like it ⭐️Read the Medium blog for more details.Documentation pagesOn thedocumentation pagesyou can find detailed information about the working of thebnlearnwith many examples.InstallationIt is advisable to create a new environment (e.g. with Conda).condacreate-nenv_bnlearnpython=3.10
condaactivateenv_bnlearnInstall bnlearn from PyPIpipinstallbnlearnInstall bnlearn from github sourcepipinstallgit+https://github.com/erdogant/bnlearnThe following functions are available after installation:# Import libraryimportbnlearnasbn# Structure learningbn.structure_learning.fit()# Compute edge strength with the test statisticbn.independence_test(model,df,test='chi_square',prune=True)# Parameter learningbn.parameter_learning.fit()# Inferencebn.inference.fit()# Make predictionsbn.predict()# Based on a DAG, you can sample the number of samples you want.bn.sampling()# Load well known examples to play arround with or load your own .bif file.bn.import_DAG()# Load simple dataframe of sprinkler dataset.bn.import_example()# Compare 2 graphsbn.compare_networks()# Plot graphbn.plot()# To make the directed grapyh undirectedbn.to_undirected()# Convert to one-hot datamatrixbn.df2onehot()# Derive the topological ordering of the (entire) graphbn.topological_sort()# See below for the exact working of the functionsThe following methods are also included:inferencesamplingcomparing two networksloading bif filesconversion of directed to undirected graphsMethod overviewLearning 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.ExhaustivesearchHillclimbsearchNaiveBayesTreeSearchChow-liuTree-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.ExamplesA structured overview of all examples are now available on thedocumentation pages.Structure learningExample: Learn structure on the Sprinkler dataset based on a simple dataframeExample: Comparison method and scoring types types for structure learningExample: Learn structure on  more complex dataset (Asia)Parameter learningExample: Parameter learning using a DAG and dataframeInferencesExample: Make predictions on a dataframe using inferenceSamplingExample: Sampling to create datasetsComplete examplesExample: Create a Bayesian Network, learn its parameters from data and perform the inferenceExample: Use case in the medical domainExample: Use case TitanicPlottingExample: Interactive plottingExample: Static plottingExample: Comparison of two networksVariousExample: Saving and loading of bnlearn modelsExample: Data conversions such as creating sparse datamatrix from source-target and weightsExample: Load DAG from BIF filesVarious basic examplesimportbnlearnasbn# Example dataframe sprinkler_data.csv can be loaded with:df=bn.import_example()# df = pd.read_csv('sprinkler_data.csv')df looks like thisCloudySprinklerRainWet_Grass0010111111210113001141011..............99500009961000997001099811019991011model=bn.structure_learning.fit(df)# Compute edge strength with the chi_square test statisticmodel=bn.independence_test(model,df)G=bn.plot(model)Choosing various methodtypes and scoringtypes: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 Learningimportbnlearnasbn# Import dataframedf=bn.import_example()# As an example we set the CPD at False which returns an "empty" DAGmodel=bn.import_DAG('sprinkler',CPD=False)# Now we learn the parameters of the DAG using the dfmodel_update=bn.parameter_learning.fit(model,df)# Make plotG=bn.plot(model_update)Example: Inferenceimportbnlearnasbnmodel=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 inferencequery=bn.inference.fit(model,variables=['Rain'],evidence={'Cloudy':1})print(query)print(query.df)Referenceshttps://erdogant.github.io/bnlearn/http://pgmpy.orghttps://programtalk.com/python-examples/pgmpy.factors.discrete.TabularCPD/http://www.bnlearn.com/bnrepository/ContributorsSetting up and maintaining bnlearn has been possible thanks to users and contributors. Thanks to:CitationPlease citebnlearnin your publications if this is useful for your research. See column right for citation information.MaintainerErdogan Taskesen, github:erdogantContributions are welcome.If you wish to buy me aCoffeefor this work, it is very appreciated :)