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
fitParameters |
latentVariables |
learnBN |
learnDAG |
learnParameters |
learnPDAG |
learnPAG |
isConstraintBased |
isScoreBased |
useExtendedGreedyHillClimbing |
useGreedyHillClimbing |
useGreedyThickThinning |
useK2 |
useLocalSearchWithTabuList |
useMIIC |
usePC |
useFCI |
useFCIChi2Test |
useFCIG2Test |
setFCIAlpha |
setFCIMaxPathLength |
addForbiddenArc |
addMandatoryArc |
addNoChildrenNode |
addNoParentNode |
addPossibleEdge |
eraseForbiddenArc |
eraseMandatoryArc |
eraseNoChildrenNode |
eraseNoParentNode |
erasePossibleEdge |
||
setMaxIndegree |
setSliceOrder |
setTotalOrder |
allowArcAdditions |
allowArcDeletions |
allowArcReversals |
allowArcTriangleDeletions |
useBDeuPrior |
useDirichletPrior |
useSmoothingPrior |
useScoreAIC |
useScoreBD |
useScoreBDeu |
useScoreBIC |
useScorefNML |
useScoreK2 |
useScoreLog2Likelihood |
||
useMDLCorrection |
useNMLCorrection |
useNoCorrection |
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 |
chi2 |
correctedMutualInformation |
databaseWeight |
domainSize |
G2 |
idFromName |
nameFromId |
names |
nbCols |
nbRows |
hasMissingValues |
logLikelihood |
mutualInformation |
pseudoCount |
rawPseudoCount |
recordWeight |
score |
setDatabaseWeight |
setRecordWeight |
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 bypyagrum.BNLearner.useEMand theEM*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 modalitiesmissingSymbols (list of str) – list of strings that will be interpreted as missing values (by default :
?)
- BNLearner(learner) -> BNLearner
- Parameters:
learner (
pyagrum.BNLearner) – the BNLearner to copy
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:
(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
Returns a float corresponding to the minimal difference between two consecutive log-likelihoods under which the EM parameter learning algorithm stops. |
|
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. |
|
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. |
|
Returns a float indicating EM’s time limit when the max time stopping criterion is used by the EM parameter learning algorithm. |
|
Returns a float corresponding to the minimal log-likelihood’s evolution rate under which the EM parameter learning algorithm stops its iterations. |
|
Return the period size used by the EM stopping criterion check. |
|
Returns an int representing the state of the EM algorithm. |
|
Return a human-readable message describing the current state of the EM algorithm. |
|
Returns a Boolean indicating whether the EM parameter learning algorithm is in a verbose mode. |
|
Disables the minimal difference between two consecutive log-likelihoods as a stopping criterion for the EM parameter learning algorithm. |
|
Do not limit EM to perform a maximal number of iterations. |
|
Allow EM to learn parameters for an infinite amount of time. |
|
Disables the minimal log-likelihood’s evolution rate as an EM parameter learning stopping criterion. |
|
Enforces that the minimal difference between two consecutive log-likelihoods is a stopping criterion for the EM parameter learning algorithm. |
|
Enables a limit on the number of iterations performed by EM. |
|
Forbid EM to run more than a given amount of time. |
|
Enables the minimal log-likelihood’s evolution rate as an EM parameter learning stopping criterion. |
|
Returns a Boolean indicating whether the minimal difference between two consecutive log-likelihoods is a stopping criterion for the EM parameter learning algorithm. |
|
Returns a Boolean indicating whether the max number of iterations is used by EM as a stopping criterion. |
|
Returns a Boolean indicating whether the max time criterion is used as an EM stopping criterion. |
|
Returns a Boolean indicating whether the minimal log-likelihood’s evolution rate is considered as a stopping criterion by the EM parameter learning algorithm. |
|
Returns the number of iterations performed by the EM parameter learning algorithm. |
|
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. |
|
Enforces a limit on the number of expectation/maximization steps performed by EM. |
|
Adds a constraint on the time that EM is allowed to run for learning parameters. |
|
Enforces that the minimal log-likelihood’s evolution rate is considered by the EM parameter learning algorithm as a stopping criterion. |
|
Set the period size for the EM stopping criterion check. |
|
Sets or unsets the verbosity of the EM parameter learning algorithm. |
|
Compute the G2 statistic and p-value of two columns of the database, given a list of other columns. |
|
Forbid the arc passed in argument to be added during structure learning (methods |
|
Allow an arc to be added if necessary during structure learning (methods |
|
Add to structure learning algorithms the constraint that this node cannot have any children. |
|
Add the constraint that this node cannot have any parent. |
|
assign a new possible edge |
|
Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc addition operations or not. |
|
Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc deletion operations or not. |
|
Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc reveral operations (changing the direction of the arc) or not. |
|
Sets whether ExtendedGreedyHillClimbing and LocalSearchWithTabuList are allowed to perform arc triangle deletion operations or not. |
|
Compute the chi2 statistic and p-value of two columns of the database, given a list of other columns. |
|
Copy the state of the given |
|
Compute the corrected (log2) mutual information between two columns, given a list of other columns. |
|
Get the database weight which is given as an equivalent sample size. |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Return the domain size of the variable with the given name. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Allow the arc to be added if necessary. |
|
Remove in structure learning algorithms the constraint that this node cannot have any children. |
|
Remove the constraint that this node cannot have any parent. |
|
Allow the 2 arcs to be added if necessary. |
|
Return whether the constraint-based algorithms raise an error when the learned DAG exceeds the maximum indegree (see |
|
Return whether FCI raises an error on an invalid learned PAG (see |
|
Return whether FCI exhaustive separating-set mode is enabled. |
|
Fit the parameters of a BayesNet in place using this learner’s database. |
|
Forbids the use of EM for parameter learning. |
|
Return the number of threads used by the BNLearner during structure and parameter learning. |
|
Returns whether arc reversals are allowed in the thin phase of greedy thick-thinning. |
|
Indicates whether there are missing values in the database. |
|
The error at the start of each period of the last run: one value every |
|
Return wether the current learning method is constraint-based or not. |
|
Check if the number of threads use by the learner is the default one or not. |
|
Return wether the current learning method is score-based or not. |
|
returns a Boolean indicating whether EM is used for parameter learning when the database contains missing values. |
|
Returns the list of latent variables discovered by MIIC. |
|
Learns a BayesNet (both parameters and structure) from the BNLearner’s database |
|
learn a structure from a file |
|
learn the essential graph of the Markov equivalence class of the data |
|
Learn a Partial Ancestral Graph (PAG) from the BNLearner’s database using FCI. |
|
learn a partially directed acyclic graph (PDAG) from the BNLearner’s database |
|
Creates a Bayes net whose structure corresponds to that passed in argument or to the last structure learnt by Method |
|
Compute the log-likelihood of some columns of the database, given a list of other columns. |
|
Return whether the last learning of the selected constraint-based algorithm gave a DAG ( |
|
Compute the (log2) mutual information between two columns, given a list of other columns. |
|
Return the number of columns in the database |
|
Return the number of row in the database |
|
access to pseudo-count (priors taken into account) |
|
computes the pseudoCount (taking priors into account) of the list of variables as a list of floats. |
|
Get the weight of the ith record |
|
Returns the value of the score currently in use by the BNLearner of a variable given a set of other variables |
|
Set the database weight which is given as an equivalent sample size. |
|
Choose what the constraint-based algorithms (PC, FCI, MIIC) do when the learned DAG exceeds the maximum indegree. |
|
Set the significance threshold (alpha) for independence tests used by FCI. |
|
Choose what FCI does when the learned PAG is not valid. |
|
Enable or disable exhaustive separating-set mode for the FCI skeleton phase. |
|
Set the maximum conditioning set size for independence tests used by FCI. |
|
Enable or disable arc reversals during the thin phase of greedy thick-thinning. |
|
Sets the initial structure (DAG) used by the structure learning algorithm. |
|
Set the maximum number of parents of a node of the learned structure. |
|
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. |
|
Set the significance threshold (α) used by the PC algorithm to decide whether two variables are conditionally independent. |
|
Set the maximum size of conditioning sets considered by the PC algorithm. |
|
Set whether to use the stable variant of the PC algorithm. |
|
Set the ordering strategy used when orienting unshielded colliders in the PC algorithm. |
|
Adds a constraint to the structure learning algorithm by fixing the set of possible edges. |
|
Add a constraint by fixing the set of possible edges as a |
|
Set the weight of the ith record |
|
Set a partial order on the nodes. |
|
Sets a total order on a set of nodes (not necessarily all the nodes). |
|
Returns a dictionary containing the current state of the BNLearner. |
|
The BDeu prior adds weight to all the cells of the counting tables. |
|
Select the chi-squared (χ²) independence test for the PC algorithm. |
|
Use the Dirichlet prior. |
|
Sets whether we use EM for parameter learning or not, depending on the value of epsilon. |
|
Enforces that EM with the log-likelihood min difference criterion will be used for parameter learning whenever the dataset contains missing values. |
|
Enforces that EM with the log-likelihood min evolution rate stopping criterion will be used for parameter learning when the dataset contains missing values. |
|
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. |
|
Indicate that we wish to use the FCI (Fast Causal Inference) algorithm. |
|
Select the chi-squared (χ²) independence test for the FCI algorithm. |
|
Select the G² (log-likelihood ratio) independence test for the FCI algorithm. |
|
Select the G² (log-likelihood ratio) independence test for the PC algorithm. |
|
Indicate that we wish to use a greedy hill climbing algorithm. |
|
Indicate that we wish to use the greedy thick-thinning algorithm. |
|
Indicate to use the K2 algorithm (which needs a total ordering of the variables). |
|
Indicate that we wish to use a local search with tabu list |
|
Indicate that we wish to use the MDL correction for MIIC |
|
Indicate that we wish to use MIIC. |
|
Indicate that we wish to use the NML correction for MIIC |
|
Indicate that we wish to use the NoCorr correction for MIIC |
|
Use no prior. |
|
Indicate that we wish to use the PC (Peter-Clark) algorithm. |
|
Indicate that we wish to use an AIC score. |
|
Indicate that we wish to use a BD score. |
|
Indicate that we wish to use a BDeu score. |
|
Indicate that we wish to use a BIC score. |
|
Indicate that we wish to use a K2 score. |
|
Indicate that we wish to use a Log2Likelihood score. |
|
Indicate that we wish to use a fNML (factorized normalized maximum likelihood) score. |
|
Use the prior smoothing. |
|
References of the members
Tomi Silander, Teemu Roos, Petri Kontkanen, and Petri Myllymäki. Factorized normalized maximum likelihood criterion for learning Bayesian network structures. In Manfred Jaeger and Thomas D. Nielsen, editors, Proceedings of the 4th European Workshop on Probabilistic Graphical Models (PGM 2008), 257–264. Hirtshals, Denmark, 2008. URL: https://pgm08.cs.aau.dk/Papers/29_Paper.pdf.
Jiji Zhang. On the completeness of orientation rules for causal discovery in the presence of latent confounders and selection bias. Artificial Intelligence, 172(16–17):1873–1896, 2008. URL: https://www.sciencedirect.com/science/article/pii/S0004370208001008, doi:10.1016/j.artint.2008.08.001.