Learning

pyAgrum provides a complete framework for learning Bayesian networks from data. It includes various algorithms for structure learning, parameter learning, and model evaluation. The library supports both score-based and constraint-based approaches, allowing users to choose the method that best fits their needs.

pyAgrum brings together all Bayesian network learning processes in a single, easy-to-use class: pyagrum.BNLearner. This class provides direct access to complete learning algorithms and their parameters (such as priors, scores, constraints, etc.), and also offers low-level functions that facilitate the development of new learning algorithms (for example, computing chi² or conditional likelihood on the dataset).

BNLearner allows to choose :

  • the structure learning algorithm (MIIC, Greedy Hill Climbing, K2, etc.),

  • the parameter learning method (including EM),

  • the scoring function (BDeu, AIC, etc.) for score-based algorithms,

  • the prior (smoothing, Dirichlet, etc.),

  • the constraints (e.g., forbidding certain arcs, specifying a partial order among variables, etc.),

  • the correction method (NML, etc.) for the MIIC algorithm,

  • and many low-level functions, such as computing the chi², G² score, or the conditional likelihood on the dataset.

pyagrum.BNLearner is able to learn a Bayesian network from a database (a pandas.DataFrame) or from a csv file.

Class BNLearner

Methods for performing learning:

fitParameters

latentVariables

learnBN

learnDAG

learnParameters

learnPDAG

learnPAG

Structure learning algorithms:

isConstraintBased

isScoreBased

useExtendedGreedyHillClimbing

useGreedyHillClimbing

useGreedyThickThinning

useK2

useLocalSearchWithTabuList

useMIIC

usePC

useFCI

useFCIChi2Test

useFCIG2Test

setFCIAlpha

setFCIMaxPathLength

Managing structure learning constraints:

addForbiddenArc

addMandatoryArc

addNoChildrenNode

addNoParentNode

addPossibleEdge

eraseForbiddenArc

eraseMandatoryArc

eraseNoChildrenNode

eraseNoParentNode

erasePossibleEdge

setMaxIndegree

setSliceOrder

setTotalOrder

Managing learning operations allowed:

allowArcAdditions

allowArcDeletions

allowArcReversals

allowArcTriangleDeletions

Scores and priors (for structure learning):

useBDeuPrior

useDirichletPrior

useSmoothingPrior

useScoreAIC

useScoreBD

useScoreBDeu

useScoreBIC

useScorefNML

useScoreK2

useScoreLog2Likelihood

useMDLCorrection

useNMLCorrection

useNoCorrection

EM parameter learning:

EMdisableEpsilon

EMdisableMaxIter

EMdisableMaxTime

EMdisableMinEpsilonRate

EMEpsilon

EMHistory

EMMaxIter

EMMaxTime

EMMinEpsilonRate

EMStateApproximationScheme

EMStateMessage

EMVerbosity

EMenableEpsilon

EMenableMaxIter

EMenableMaxTime

EMenableMinEpsilonRate

forbidEM

EMisEnabledEpsilon

EMisEnabledMaxIter

EMisEnabledMaxTime

EMisEnabledMinEpsilonRate

isUsingEM

EMnbrIterations

EMsetEpsilon

EMsetMaxIter

EMsetMaxTime

EMsetMinEpsilonRate

EMsetVerbosity

useEM

useEMWithDiffCriterion

useEMWithRateCriterion

Database inspection / direct requesting:

chi2

correctedMutualInformation

databaseWeight

domainSize

G2

idFromName

nameFromId

names

nbCols

nbRows

hasMissingValues

logLikelihood

mutualInformation

pseudoCount

rawPseudoCount

recordWeight

score

setDatabaseWeight

setRecordWeight

Fine-tuning the behavior of the BNLearner:

copyState

getNumberOfThreads

isGumNumberOfThreadsOverriden

setNumberOfThreads

class pyagrum.BNLearner(*args)

This class provides functionality for learning Bayesian Networks from data.

The stopping criteria and the verbosity (pyagrum.BNLearner.setEpsilon, pyagrum.BNLearner.setMaxIter, pyagrum.BNLearner.setMaxTime, etc.) concern the structure learning: a setter applies to every structure-learning algorithm, a getter returns the value of the selected algorithm, and the results of its last learning (pyagrum.BNLearner.nbrIterations, pyagrum.BNLearner.history, etc.). EM has its own stopping criteria, set by pyagrum.BNLearner.useEM and the EM* methods.

BNLearner(filename,inducedTypes=True) -> BNLearner
Parameters:
  • source (str or pandas.DataFrame) – the data to learn from

  • missingSymbols (list of str) – list of strings that will be interpreted as missing values (by default : ?)

  • inducedTypes (Bool) – whether BNLearner should try to automatically find the type of each variable

BNLearner(filename,src) -> BNLearner
Parameters:
  • source (str or pandas.DataFrame) – the data to learn from

  • src (pyagrum.BayesNet) – the Bayesian network used to find those modalities

  • missingSymbols (list of str) – list of strings that will be interpreted as missing values (by default : ?)

BNLearner(learner) -> BNLearner
Parameters:

Scientific notes

BNLearner learns a Bayesian network from a complete database of discrete variables, by a score-based search, by conditional independence tests, or by MIIC (the default algorithm, given by pyagrum.config["learning", "BNLearnerPreferredAlgo"]); the parameters are then estimated from the counts.

Scores (useScoreXXX, BDeu by default). They are decomposable, in bits (base 2 logarithms). With \(N_{ijk}\) the count of \(X_i = k\) and of the \(j\)-th configuration of its \(q_i\) parent configurations, \(r_i\) the domain size of \(X_i\) and \(N\) the size of the database:

\[\mathrm{LL}_i = \sum_{j,k} N_{ijk} \log_2 \frac{N_{ijk}}{N_{ij}}, \qquad \mathrm{AIC}_i = \mathrm{LL}_i - q_i(r_i-1)\log_2 e, \qquad \mathrm{BIC}_i = \mathrm{LL}_i - \tfrac{1}{2}\, q_i(r_i-1) \log_2 N,\]
\[\mathrm{BD}_i = \sum_{j=1}^{q_i} \Big[\log_2 \frac{\Gamma(N'_{ij})}{\Gamma(N_{ij}+N'_{ij})} + \sum_{k=1}^{r_i} \log_2 \frac{\Gamma(N_{ijk}+N'_{ijk})}{\Gamma(N'_{ijk})}\Big]\]

(AIC [1], BIC [2], BD [3]). AIC and BIC are the criteria of Akaike and Schwarz expressed in bits (divided by \(\ln 2\)). BD takes its hyperparameters \(N'_{ijk}\) from the prior, which is then mandatory; BDeu [4] uses \(N'_{ijk} = 1/(r_i q_i)\) (an equivalent sample size of 1) and K2 [5] \(N'_{ijk} = 1\). A prior given to another score adds its pseudo-counts to the counts (to these implicit hyperparameters for BDeu and K2, with a warning).

fNML [6] replaces the BIC penalty by the regret of the normalized maximum likelihood of each conditional distribution, without any parameter to tune: \(\mathrm{fNML}_i = \mathrm{LL}_i - \sum_{j=1}^{q_i} \log_2 C(r_i, N_{ij})\), with \(C(r, n) = \sum_{h_1+\dots+h_r=n} \frac{n!}{h_1!\cdots h_r!} \prod_k (h_k/n)^{h_k}\). \(C\) is tabulated for \(r \le 5\) and \(n < 1000\), computed beyond by the recurrence of [7] over \(r\), starting for \(n \ge 1000\) from the asymptotic expansion of \(C(2, n)\) given by [8].

Priors (useXXXPrior, none by default, weight \(w\) given by pyagrum.config["learning", "priorWeight"], 1): pseudo-counts \(N'_{ijk} = w\) for the smoothing (Laplace for \(w=1\)); \(w/(r_i q_i)\) for BDeu; \(w\) times the joint distribution of the family for a Dirichlet prior from a Bayesian network, or its frequency in another database.

Score-based search. Greedy hill climbing applies the best arc addition, removal or reversal until no change improves the score; the local search with tabu list [9] accepts up to tabuNbDecrease (2) consecutive decreases with a tabu list of tabuListSize (100) changes and returns the best graph found; greedy thick-thinning adds arcs while the score improves, then removes them; K2 [5] is the greedy search restricted to the arc additions consistent with a given order, with the chosen score.

Independence tests (PC, FCI). The chi2 or G2 statistic of \(X \perp Y \mid Z\) is computed on the non empty part of the table: a configuration \(z\) with \(r_z\) non empty rows and \(c_z\) non empty columns brings \((r_z-1)(c_z-1)\) degrees of freedom [10], and independence is accepted when the p-value exceeds alpha (pyagrum.config["learning", "alpha"], 0.05). PC [11][12] is stable by default [13]; conflicting colliders become double arcs before the Meek rules (pyagrum.MeekRules). FCI gives a PAG (pyagrum.PAG), turned into a DAG through its representative MAG.

MIIC [14] removes the edge \(X - Y\) as soon as a conditioning set \(U\) (grown by the best contributors) gives \(N\,I(X;Y \mid U) - k_{X;Y \mid U} \le 0\) (information in bits). The complexity is \(k = \tfrac12 (r_X-1)(r_Y-1)\, r_U \log_2 N\) for the MDL correction (default) [15], and for the NML one the sum, over the configurations \(u\), of \(\tfrac12 [\sum_x \log_2 C(r_Y, N_{xu}) - \log_2 C(r_Y, N_u) + \sum_y \log_2 C(r_X, N_{yu}) - \log_2 C(r_X, N_u)]\), \(C(r, n)\) being the multinomial parametric complexity [8][7]. The unshielded triples are then oriented by decreasing probability of collider, computed from the 3-point information; contradictory orientations give the double arcs of latentVariables. The DAGs of the constraint-based algorithms are oriented by pyagrum.MeekRules.

Parameters. \(\hat\theta_{ijk} = (N_{ijk} + N'_{ijk})/(N_{ij} + N'_{ij})\), the prior’s pseudo-counts included; learnBN adds the implicit hyperparameters of the score (BDeu, K2). With missing values and useEM, EM [16][17] starts from the estimate on the complete rows, mixed as \((1-\nu)\,\theta + \nu\,\text{random}\) with \(\nu\) = pyagrum.config["learning", "emNoise"] (0.1); each iteration replaces the counts by their expectations given the current network, until the relative variation of the log-likelihood is below epsilon (or its variation, or 10 000 iterations). EM also stops after 4 consecutive decreases of the log-likelihood; when it ends on decreases, the network that preceded them is returned.

Implementation limit. Structure learning needs a complete database; without prior, a parent configuration absent from the data makes the maximum likelihood undefined and raises an error.

Methods

EMEpsilon()

Returns a float corresponding to the minimal difference between two consecutive log-likelihoods under which the EM parameter learning algorithm stops.

EMHistory()

Returns a list containing the values recorded after each expectation/maximization iteration of the EM parameter learning algorithm: the absolute difference between two consecutive log-likelihoods.

EMMaxIter()

Returns an int containing the max number of iterations the EM parameter learning algorithm is allowed to perform when the max iterations stopping criterion is enabled.

EMMaxTime()

Returns a float indicating EM’s time limit when the max time stopping criterion is used by the EM parameter learning algorithm.

EMMinEpsilonRate()

Returns a float corresponding to the minimal log-likelihood’s evolution rate under which the EM parameter learning algorithm stops its iterations.

EMPeriodSize()

Return the period size used by the EM stopping criterion check.

EMStateApproximationScheme()

Returns an int representing the state of the EM algorithm.

EMStateMessage()

Return a human-readable message describing the current state of the EM algorithm.

EMVerbosity()

Returns a Boolean indicating whether the EM parameter learning algorithm is in a verbose mode.

EMdisableEpsilon()

Disables the minimal difference between two consecutive log-likelihoods as a stopping criterion for the EM parameter learning algorithm.

EMdisableMaxIter()

Do not limit EM to perform a maximal number of iterations.

EMdisableMaxTime()

Allow EM to learn parameters for an infinite amount of time.

EMdisableMinEpsilonRate()

Disables the minimal log-likelihood’s evolution rate as an EM parameter learning stopping criterion.

EMenableEpsilon()

Enforces that the minimal difference between two consecutive log-likelihoods is a stopping criterion for the EM parameter learning algorithm.

EMenableMaxIter()

Enables a limit on the number of iterations performed by EM.

EMenableMaxTime()

Forbid EM to run more than a given amount of time.

EMenableMinEpsilonRate()

Enables the minimal log-likelihood’s evolution rate as an EM parameter learning stopping criterion.

EMisEnabledEpsilon()

Returns a Boolean indicating whether the minimal difference between two consecutive log-likelihoods is a stopping criterion for the EM parameter learning algorithm.

EMisEnabledMaxIter()

Returns a Boolean indicating whether the max number of iterations is used by EM as a stopping criterion.

EMisEnabledMaxTime()

Returns a Boolean indicating whether the max time criterion is used as an EM stopping criterion.

EMisEnabledMinEpsilonRate()

Returns a Boolean indicating whether the minimal log-likelihood’s evolution rate is considered as a stopping criterion by the EM parameter learning algorithm.

EMnbrIterations()

Returns the number of iterations performed by the EM parameter learning algorithm.

EMsetEpsilon()

Enforces that the minimal difference between two consecutive log-likelihoods is chosen as a stopping criterion of the EM parameter learning algorithm and specifies the threshold on this criterion.

EMsetMaxIter()

Enforces a limit on the number of expectation/maximization steps performed by EM.

EMsetMaxTime()

Adds a constraint on the time that EM is allowed to run for learning parameters.

EMsetMinEpsilonRate()

Enforces that the minimal log-likelihood’s evolution rate is considered by the EM parameter learning algorithm as a stopping criterion.

EMsetPeriodSize()

Set the period size for the EM stopping criterion check.

EMsetVerbosity()

Sets or unsets the verbosity of the EM parameter learning algorithm.

G2()

Compute the G2 statistic and p-value of two columns of the database, given a list of other columns.

addForbiddenArc()

Forbid the arc passed in argument to be added during structure learning (methods learnDAG() or learnBN()).

addMandatoryArc()

Allow an arc to be added if necessary during structure learning (methods learnDAG() or learnBN()).

addNoChildrenNode()

Add to structure learning algorithms the constraint that this node cannot have any children.

addNoParentNode()

Add the constraint that this node cannot have any parent.

addPossibleEdge()

assign a new possible edge

allowArcAdditions()

Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc addition operations or not.

allowArcDeletions()

Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc deletion operations or not.

allowArcReversals()

Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc reveral operations (changing the direction of the arc) or not.

allowArcTriangleDeletions()

Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc triangle deletion operations or not.

chi2()

Compute the chi2 statistic and p-value of two columns of the database, given a list of other columns.

copyState()

Copy the state of the given pyagrum.BNLearner (as argument).

correctedMutualInformation()

Compute the corrected (log2) mutual information between two columns, given a list of other columns.

currentTime()

databaseWeight()

Get the database weight which is given as an equivalent sample size.

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

domainSize()

Return the domain size of the variable with the given name.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseForbiddenArc()

Allow the arc to be added if necessary.

eraseMandatoryArc()

eraseNoChildrenNode()

Remove in structure learning algorithms the constraint that this node cannot have any children.

eraseNoParentNode()

Remove the constraint that this node cannot have any parent.

erasePossibleEdge()

Allow the 2 arcs to be added if necessary.

errorOnExceededMaxIndegree()

Return whether the constraint-based algorithms raise an error when the learned DAG exceeds the maximum indegree (see setErrorOnExceededMaxIndegree).

fciErrorOnInvalidPAG()

Return whether FCI raises an error on an invalid learned PAG (see setFCIErrorOnInvalidPAG).

fciExhaustiveSepSet()

Return whether FCI exhaustive separating-set mode is enabled.

fitParameters()

Fit the parameters of a BayesNet in place using this learner’s database.

forbidEM()

Forbids the use of EM for parameter learning.

getNumberOfThreads()

Return the number of threads used by the BNLearner during structure and parameter learning.

greedyThickThinningReversals()

Returns whether arc reversals are allowed in the thin phase of greedy thick-thinning.

hasMissingValues()

Indicates whether there are missing values in the database.

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

idFromName()

isConstraintBased()

Return wether the current learning method is constraint-based or not.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isGumNumberOfThreadsOverriden()

Check if the number of threads use by the learner is the default one or not.

isScoreBased()

Return wether the current learning method is score-based or not.

isUsingEM()

returns a Boolean indicating whether EM is used for parameter learning when the database contains missing values.

latentVariables()

Returns the list of latent variables discovered by MIIC.

learnBN()

Learns a BayesNet (both parameters and structure) from the BNLearner’s database

learnDAG()

learn a structure from a file

learnEssentialGraph()

learn the essential graph of the Markov equivalence class of the data

learnPAG()

Learn a Partial Ancestral Graph (PAG) from the BNLearner’s database using FCI.

learnPDAG()

learn a partially directed acyclic graph (PDAG) from the BNLearner’s database

learnParameters()

Creates a Bayes net whose structure corresponds to that passed in argument or to the last structure learnt by Method learnDAG(), and whose parameters are learnt from the BNLearner’s database.

logLikelihood()

Compute the log-likelihood of some columns of the database, given a list of other columns.

maxIndegreeExceeded()

Return whether the last learning of the selected constraint-based algorithm gave a DAG (learnDAG() or learnBN()) exceeding the maximum indegree.

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

mutualInformation()

Compute the (log2) mutual information between two columns, given a list of other columns.

nameFromId()

names()

nbCols()

Return the number of columns in the database

nbRows()

Return the number of row in the database

nbrIterations()

periodSize()

pseudoCount()

access to pseudo-count (priors taken into account)

rawPseudoCount()

computes the pseudoCount (taking priors into account) of the list of variables as a list of floats.

recordWeight()

Get the weight of the ith record

score()

Returns the value of the score currently in use by the BNLearner of a variable given a set of other variables

setDatabaseWeight()

Set the database weight which is given as an equivalent sample size.

setEpsilon()

setErrorOnExceededMaxIndegree()

Choose what the constraint-based algorithms (PC, FCI, MIIC) do when the learned DAG exceeds the maximum indegree.

setFCIAlpha()

Set the significance threshold (alpha) for independence tests used by FCI.

setFCIErrorOnInvalidPAG()

Choose what FCI does when the learned PAG is not valid.

setFCIExhaustiveSepSet()

Enable or disable exhaustive separating-set mode for the FCI skeleton phase.

setFCIMaxPathLength()

Set the maximum conditioning set size for independence tests used by FCI.

setGreedyThickThinningReversals()

Enable or disable arc reversals during the thin phase of greedy thick-thinning.

setInitialDAG()

Sets the initial structure (DAG) used by the structure learning algorithm.

setMaxIndegree()

Set the maximum number of parents of a node of the learned structure.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setNumberOfThreads()

If the parameter n passed in argument is different from 0, the BNLearner will use n threads during learning, hence overriding pyagrum default number of threads.

setPCAlpha()

Set the significance threshold (α) used by the PC algorithm to decide whether two variables are conditionally independent.

setPCMaxCondSetSize()

Set the maximum size of conditioning sets considered by the PC algorithm.

setPCStable()

Set whether to use the stable variant of the PC algorithm.

setPCUnshieldedColliderSorted()

Set the ordering strategy used when orienting unshielded colliders in the PC algorithm.

setPeriodSize()

setPossibleEdges()

Adds a constraint to the structure learning algorithm by fixing the set of possible edges.

setPossibleSkeleton()

Add a constraint by fixing the set of possible edges as a pyagrum.UndiGraph.

setRecordWeight()

Set the weight of the ith record

setSliceOrder()

Set a partial order on the nodes.

setTotalOrder()

Sets a total order on a set of nodes (not necessarily all the nodes).

setVerbosity()

state()

Returns a dictionary containing the current state of the BNLearner.

useBDeuPrior()

The BDeu prior adds weight to all the cells of the counting tables.

useChi2Test()

Select the chi-squared (χ²) independence test for the PC algorithm.

useDirichletPrior()

Use the Dirichlet prior.

useEM()

Sets whether we use EM for parameter learning or not, depending on the value of epsilon.

useEMWithDiffCriterion()

Enforces that EM with the log-likelihood min difference criterion will be used for parameter learning whenever the dataset contains missing values.

useEMWithRateCriterion()

Enforces that EM with the log-likelihood min evolution rate stopping criterion will be used for parameter learning when the dataset contains missing values.

useExtendedGreedyHillClimbing()

Indicate that we wish to use a greedy hill climbing algorithm, controlling the set of arc operations that this learning algorithm is allowed to exploit.

useFCI()

Indicate that we wish to use the FCI (Fast Causal Inference) algorithm.

useFCIChi2Test()

Select the chi-squared (χ²) independence test for the FCI algorithm.

useFCIG2Test()

Select the G² (log-likelihood ratio) independence test for the FCI algorithm.

useG2Test()

Select the G² (log-likelihood ratio) independence test for the PC algorithm.

useGreedyHillClimbing()

Indicate that we wish to use a greedy hill climbing algorithm.

useGreedyThickThinning()

Indicate that we wish to use the greedy thick-thinning algorithm.

useK2()

Indicate to use the K2 algorithm (which needs a total ordering of the variables).

useLocalSearchWithTabuList()

Indicate that we wish to use a local search with tabu list

useMDLCorrection()

Indicate that we wish to use the MDL correction for MIIC

useMIIC()

Indicate that we wish to use MIIC.

useNMLCorrection()

Indicate that we wish to use the NML correction for MIIC

useNoCorrection()

Indicate that we wish to use the NoCorr correction for MIIC

useNoPrior()

Use no prior.

usePC()

Indicate that we wish to use the PC (Peter-Clark) algorithm.

useScoreAIC()

Indicate that we wish to use an AIC score.

useScoreBD()

Indicate that we wish to use a BD score.

useScoreBDeu()

Indicate that we wish to use a BDeu score.

useScoreBIC()

Indicate that we wish to use a BIC score.

useScoreK2()

Indicate that we wish to use a K2 score.

useScoreLog2Likelihood()

Indicate that we wish to use a Log2Likelihood score.

useScorefNML()

Indicate that we wish to use a fNML (factorized normalized maximum likelihood) score.

useSmoothingPrior()

Use the prior smoothing.

verbosity()

References of the members