Classifier using Bayesian networks
pyagrum.skbn.BNClassifier is a scikit-learn-compatible
classifier built on top of a pyagrum.BayesNet. It implements the standard fit /
predict / predict_proba interface, making it easy to integrate Bayesian network
classifiers into existing scikit-learn pipelines.
- class pyagrum.skbn.BNClassifier(*, type_processor, learningMethod='MIIC', prior=None, scoringType='BIC', constraints=None, priorWeight=None, possibleSkeleton=None, DirichletCsv=None, TANSignificance=None, usePR=False, beta=1, significant_digit=10)
Represents a (scikit-learn compliant) classifier which uses a BN to classify. A BNClassifier is build using
a Bayesian network,
a database and a learning algorithm and parameters
the use of DiscreteTypeProcessor to discretize with different algorithms some variables.
The classifier can be used to predict the class of new data.
The id of a node of the Bayesian network (
bn_,possibleSkeleton, the ids inconstraints) is the position of its column in the data given by the user:pyagrum.skbn.BNClassifier.fit: the columniofXhas the idi, the target the idX.shape[1];pyagrum.skbn.BNClassifier.fitFromTabular: the columnjofdata, the target included, has the idj.
A constant column is not a variable (it is removed, with a warning): its id is unused, the other ids do not move. The ids of
bn_are therefore not necessarily contiguous.- Parameters:
type_processor (
pyagrum.lib.discreteTypeProcessor.DiscreteTypeProcessor) – The processor which gives the type of each variable and discretizes the continuous ones (seecreateBNClassifier(...)to build one from simple discretization parameters).learningMethod (
str) – A string designating which learning algorithm we want to use. Possible values are: Chow-Liu, NaiveBayes, TAN, MIIC, MIICMDL, MIICNML, GHC, Tabu. GHC designates Greedy Hill Climbing. MIIC designates Multivariate Information based Inductive Causation; MIICMDL and MIICNML use MIIC with the MDL or the NML correction. TAN designates Tree-augmented NaiveBayes Tabu designates Tabu list searchingprior (
str) – A string designating the type of prior we want to use. Possible values are Smoothing, BDeu, Dirichlet and NoPrior . Note: if using Dirichlet smoothing DirichletCsv cannot be set to none By default (when prior is None) : a smoothing(0.01) is applied.scoringType (
str) – A string designating the scoring method we want to use. Since scoring is used while constructing the network and not when learning its parameters, the scoring will be ignored if using a learning algorithm with a fixed network structure such as Chow-Liu, TAN or NaiveBayes. possible values are: AIC, BIC, BD, BDeu, fNML, K2, Log2 AIC means Akaike information criterion BIC means Bayesian Information criterion BD means Bayesian-Dirichlet scoring BDeu means Bayesian-Dirichlet equivalent uniform fNML means factorized normalized maximum likelihood Log2 means log2 likelihood ratio testconstraints (
dict()) –A dictionary designating the constraints that we want to put on the structure of the Bayesian network. Ignored if using a learning algorithm where the structure is fixed such as TAN or NaiveBayes. the keys of the dictionary should be the strings “PossibleEdges” , “MandatoryArcs”, “ForbiddenArcs” and “MaxIndegree”. The format of the values should be a tuple of strings (tail,head) which designates the string arc from tail to head. For example if we put the value (“x0”.”y”) in MandatoryArcs the network will surely have an arc going from x0 to y. The value of MaxIndegree is the maximal number of parents of a node (an int >= 1, see
pyagrum.BNLearner.setMaxIndegree): it bounds the size of the CPTs.Note: PossibleEdge allows between nodes x and y allows for either (x,y) or (y,x) (or none of them) to be added to the Bayesian network, while the others are not symmetric. A node can also be given by its id (the position of its column, see the ids of the nodes in
pyagrum.skbn.BNClassifier).priorWeight (
double) – The weight used for a prior. If None,pyagrum.config['learning', 'priorWeight']is used.possibleSkeleton (
pyagrum.UndiGraph) – An undirected graph that serves as a possible skeleton for the Bayesian network. Its nodes are the ids of the nodes (the positions of the columns, seepyagrum.skbn.BNClassifier).DirichletCsv (
str) – the file name of the csv file we want to use for the dirichlet prior. Will be ignored if prior is not set to Dirichlet.TANSignificance (
float) – The level, in ]0,1], of the independence tests of the TAN classifier: a feature is kept if its dependence on the class is significant, an edge between two features is a candidate for the tree if their dependence given the class is significant (selective TAN). With 1, every feature and every edge is kept (TAN of Friedman et al.). The dropped features stay in the network as isolated nodes; if no feature is kept, a warning is emitted and the classifier predicts the prior of the class. If None,pyagrum.config['skbn', 'tanSignificance']is used when the classifier is fitted. Ignored by the other learning methods.usePR (
bool) – indicates if the threshold to choose is Precision-Recall curve’s threshold or ROC’s threshold by default. ROC curves should be used when there are roughly equal numbers of observations for each class. Precision-Recall curves should be used when there is a moderate to large class imbalance especially for the target’s class.beta (
float) – if you choose the Precision-Recall curve’s threshold, the F-beta score is maximized. By default, beta=1 to have the F1 score. A value inferior of 1 will give more weight to precision. A value superior of 1 will give more weight to recall. For example, beta = 0.5 makes precision twice as important as recall, while beta = 2 does the opposite.significant_digit – number of significant digits when computing probabilities
Scientific notes
BNClassifier is a classifier whose model is a Bayesian network over the features and the class \(Y\). The
continuous features are first discretized by a pyagrum.lib.discreteTypeProcessor.DiscreteTypeProcessor
(createBNClassifier: quantiles, 5 intervals, for the numerical features with more than 25 distinct values). The
structure is learned by pyagrum.BNLearner (MIIC [1] by default, greedy hill climbing, tabu
search) or has a fixed form: naive Bayes (\(Y\) parent of every feature), the Chow-Liu tree
[2] over the features and the class, rooted at \(Y\), or the tree-augmented naive Bayes
(TAN) [3]. Without prior given, the parameters are estimated with a smoothing prior of
weight 0.01. The id of a node is the position of its column in the data (the target, outside X in fit, comes
after its columns), so that a structural constraint given by ids keeps its meaning when a constant column is removed.
TAN. The selective TAN of [4] is learned with the level \(\alpha\) given by
TANSignificance (default: the key skbn.tanSignificance of pyagrum.config, 0.01). The features
\(X_i\) whose G-test of independence from \(Y\) (\(G^2 = 2N\,I(X_i; Y)\), \(\chi^2\) with
\((r_i-1)(r_Y-1)\) degrees of freedom) gives a p-value above \(\alpha\) are dropped (they stay in the
network as isolated nodes; if none is kept, a warning is emitted and the prior of \(Y\) is predicted). Between the
kept
features, the pairs whose conditional G-test (\(G^2 = 2N\,I(X_i; X_j \mid Y)\), \(\chi^2\) with
\((r_i-1)(r_j-1)r_Y\) degrees of freedom) gives a p-value above \(\alpha\) are dropped, and a maximum weight
spanning tree of each connected component of the remaining pairs, weighted by \(I(X_i; X_j \mid Y)\), is built
(Kruskal): the result may be a forest. [4] test each slice \(Y=y\) separately, with
\((r_i-1)(r_j-1)\) degrees of freedom, and keep the pair if one slice is significant; pyAgrum uses the
conditional test, whose asymptotic law is known. Each tree is directed from the feature that has the largest
\(I(X; Y)\), and \(Y\) is a parent of every kept feature. With \(\alpha = 1\), every feature and every
pair is kept: this is the TAN of [3].
Prediction. The posterior of \(Y\) is computed in the Markov blanket of \(Y\) only. With more than two
classes, the most probable one is predicted. With two classes, the second label \(y_1\) is predicted when
\(p = P(Y=y_1 \mid x) \geq t\), the threshold \(t\) being chosen on the training data: the point of the ROC
curve closest to \((0, 1)\), or, with usePR, the point of the precision-recall curve of maximal
\(F_\beta\). predict_proba rescales \(p\) piecewise linearly (\(p/2t\) below \(t\),
\(\frac12 + \frac{p-t}{2(1-t)}\) above) so that its largest value always gives the predicted class.
Methods
Reads the data from a csv file and separates it into an X matrix and a y column vector. |
|
Changes the name of a variable inside the Bayesian network |
|
Fits the model to the training data provided. |
|
Convenience wrapper around fit() for loading training data from a CSV file or a pandas DataFrame directly. |
|
Creates a BN classifier from an already trained pyAgrum Bayesian network. |
|
Returns a copy of the Bayesian network used by this classifier. |
|
Predicts the most likely class for each row of input data, with bn’s Markov Blanket |
|
Predicts the probability of classes for each row of input data, with bn’s Markov Blanket. |
|
Given an X and a y (or a data source : filename or pandas.DataFrame), returns a pandas.Dataframe with the prepared (especially discretized) values of the base |
|
Use the |