andrey.fges#
- andrey.fges(data, *, score_func=None, penalty_discount=1.0, ebic_gamma=1.0, equivalent_sample_size=1.0, max_parents=None, categorical=None, one_edge_faithfulness=False, knowledge=None)[source]#
Learn a CPDAG from observational data with fast greedy equivalence search (FGES).
FGES is GES [1] arranged for large sparse graphs [2]: its first forward phase adds an edge between two variables only when the graph of that single edge scores better than the empty graph, a second pass covers the unshielded noncolliders that phase left, and by default a third pass scans every pair. It returns the same kind of result as
ges(), from the same scores and the same search.- Parameters:
data (
ArrayLike) – Observed data, one row per sample. Coerced tofloat64. A DataFrame’s column names become the structure’slabels.score_func (
str|None) – Local score objective:"bic", the linear-Gaussian BIC, for continuous data."normal_scores", experimental, is"bic"on each column’s normal scores, for continuous data that are Gaussian only after an unknown increasing transformation of each column."bdeu"is the BDeu score [3] and"discrete_bic"the multinomial BIC [6], for categorical data coded by whole numbers."degen_gauss"(degenerate Gaussian) [4] and"cond_gauss"(conditional Gaussian) [5] are BIC scores for mixed data, continuous and categorical columns.Nonepicks from the declared column types:"bdeu"when every column is categorical,"cond_gauss"when some are, else"bic". A column is declared categorical bycategoricalor by a DataFrame’scategory,bool, or text type, never by its values. See Notes.metadata["score_func"]names the score the fit used: the one picked from the declared column types when this isNone.penalty_discount (
float) – Multiplier on the BIC penalty oflog(n_samples)per parameter: per parent for the linear-Gaussian BIC. Larger values give sparser graphs;1.0withebic_gamma=0.0is the standard BIC. Must be finite and non-negative. BDeu ignores it; for the multinomial BIC it weighslog(n)per free parameter of a variable’s conditional probability table.ebic_gamma (
float) – Weight on the extended-BIC term [7] of the linear-Gaussian BIC: each variable’s score adds2 * ebic_gamma * log C(n_variables - 1, n_parents), which grows with the number of parent sets a variable can choose from. Larger values give sparser graphs;0.0is the standard BIC. Must be from 0 to 1. Only"bic"and"normal_scores"use it: passing it with another score raisesValueError. See Notes.equivalent_sample_size (
float) – The equivalent sample size of the BDeu score: how many rows the uniform prior over each variable’s conditional distributions is worth. A larger value weighs the prior more against the data, and the graph can change with it. Must be finite and positive. Only"bdeu"uses it: passing it with another score raisesValueError.max_parents (
int|None) – A cap on every node’s parents, at least0: no DAG the returned CPDAG represents gives a node more thanmax_parentsparents, and some DAG reaches each node’s count. A move whose CPDAG would break the cap, in either phase, is skipped for the next best move. A cap can stop the search short of the lowest-scoring graph, which GES otherwise finds.Nonesets no cap; the forward phase then keeps its gate ofn_variables / 2. See Notes.categorical (
Sequence[str|int] |None) – The categorical columns ofdata, for a mixed-data score: column labels (strings) or 0-based positions.Nonetakes a DataFrame’scategory,bool, and text columns, never a column by its values.[]marks none. A categorical score reads every column as categorical, and a continuous score raisesValueErroron a declared column, named here or by its type. See Data types in the getting-started guide.one_edge_faithfulness (
bool) – Whether to assume one-edge faithfulness [2]: no edge is added between two variables whose one-edge graph does not improve the score over the empty graph, unless the pass that covers the unshielded noncolliders adds it.False, the default, drops the assumption: a third forward and backward pass scans every pair on the graph the first two passes reached, as GES does, so such an edge can still be added. It favors the graphs GES finds and gives up part of the time and memoryTruesaves.Truefavors time and memory on large sparse graphs and gives up the edges the one-edge screen skips. See Notes.knowledge (
Knowledge|None) – Background knowledge, aKnowledge: required and forbidden edges, the pairs allowed to be adjacent, and temporal tiers, all honored. No move adds a forbidden edge or removes a required one, and the search starts from the required edges. The result directs every edge the knowledge decides, then Meek’s rules direct the edges that follow, asKnowledgedescribes.
- Returns:
Wraps a
cpdagGraphStructure;metadata["algorithm"]is"fges"andmetadata["score"]the score of the result; lower is better. For BIC, it is the sum over variables ofn * log(residual variance) + penalty_discount * log(n) * n_parents + 2 * ebic_gamma * log C(n_variables - 1, n_parents); for BDeu,-2times the log of the structure prior times the marginal likelihood; for the multinomial BIC and the mixed-data scores, see Notes. Directed marks (->) are oriented edges, undirected (--) the ones the equivalence class leaves open. Under a mixed-data setting,metadata["categorical"]lists the categorical columns it read, by name or 0-based position.metadata["tie_break"]is the tie-break rule the fit ran under,andrey.config.tie_break, andmetadataalso records the penalties its score used, under their parameter names.- Return type:
- Raises:
TypeError – If an argument has the wrong type, such as a string for a number; the message names the method, the argument, what it accepts, and the value. Also if
categoricalis not a list of column names and positions, orknowledgeis neitherNonenor aKnowledge.ValueError – If an argument lies outside its range or is not one of its choices; the message names the method, the argument, what it accepts, and the value. Also if
datais not a 2-D numeric matrix with at least two rows and noNaNorinf, or if a column is constant; if a givenmax_parentsis below the parents some graph of the required edges ofknowledgegives a node; with a categorical score, ifdataholds a number that is not whole; or, with a mixed-data score, ifcategoricalnames a columndatalacks, or if a categorical column holds a number that is not whole. Also if a continuous score meets a column declared categorical, bycategoricalor by its type. With the BIC score, also if a column repeats another up to scale and shift given more than two rows or, with more rows than columns, is a linear function of other columns. One message names every group of copies and says to keep one column per group. Also ifknowledgenames a columndatalacks or contradicts itself, asKnowledgelists.
- Warns:
DataTypeWarning – When a mixed-data score finds no declared categorical column and so runs as the linear-Gaussian form, or when a setting reads columns that look like category codes as numbers. Each message warns once per process.
ExperimentalWarning – On the first call in a process: the method is not supported (see Limitations), and its API may change without deprecation.
Notes
When to use. FGES makes the assumptions of GES: i.i.d. observational data, no unmeasured common causes, and, with the BIC score on continuous data, linear relations with Gaussian noise. It takes the scores, penalties,
max_parents, and background knowledge ofges()(see it for the scores and how to choosepenalty_discount) and returns the equivalence class. Use it instead of GES on sparse graphs with many variables, where it takes less time. When time and memory decide and the graph is large and sparse, useone_edge_faithfulness=True, which skips the pass over every pair. When unmeasured common causes are plausible, usefci().How it works. FGES scores the one-edge graph of every pair against the empty graph under the plain BIC (the likelihood and the
penalty_discountpenalty, without the extended-BIC term ofebic_gamma, as in [2]). A pair whose one-edge graph does not improve that score by the margin a move needs gets no edge in the first forward phase, in either direction. That phase and a backward phase are the search ofges()otherwise: each target scans only the sources that pass, with the same cached candidates and worker processes, and the backward phase considers every edge. The second pass is steps fGES.9-11 of the pseudocode in Supplement 1 of [2]. For each targety, the candidate sources are the nodesmnot adjacent toythat share a neighbornwith it unlessm -> n <- y: the ends of a pathm *-* n *-* ythat is not a collider. They are recomputed from the graph after each applied move, and a target whose sources changed is scanned again. The pass runs a forward phase over these candidates without the marginal screen, then the backward phase again, so a pair that was married to orient a collider can be divorced. Unlessone_edge_faithfulness=True, a third forward and backward pass scans every pair on the graph the second pass returned, as GES does, which drops the assumption; [2] reports that this mode runs considerably longer. The paper [2] also gives FGES a parallel and cached scoring scheme, which GES here shares, and fixes the BIC penalty at 4 times the standard one for continuous data;penalty_discountkeeps the default of1.0that every method shares.Missing values. A
NaNindataraisesValueError. The score sums one term per variable over every row; terms over different rows do not sum to one dataset’s score, so the search cannot delete rows per test as conditional-independence searches do. Drop the incomplete rows yourself, which suits values missing completely at random, or usepc()orfci(), whose tests delete rows per test.Limitations. By default FGES makes no more errors than
ges(), and often fewer on denser graphs, in less time. Its time and memory still grow with the number of variables much as GES’s do, because the third pass scans every pair, so very large graphs can exceed practical time for this implementation.one_edge_faithfulness=Truetrades accuracy for speed and memory: it takes less time and holds less memory on large sparse graphs, but a pair whose variables show no link on their own is not added in the first phase, so an edge whose effect shows only once other variables are in the graph can be missed. With the standard BIC at a largepenalty_discount, as in [2], it makes more errors than GES; under the default score it can make fewer on sparse graphs and more on denser graphs. The 0.20.0 release card has the measurements.References
Examples
>>> import numpy as np >>> import pandas as pd >>> from andrey import fges >>> rng = np.random.default_rng(0) >>> x = rng.standard_normal(500) >>> y = rng.standard_normal(500) >>> z = x + y + 0.5 * rng.standard_normal(500) >>> fges(pd.DataFrame({"x": x, "y": y, "z": z})).structure.oriented_edges() [('x', 'z', 'directed'), ('y', 'z', 'directed')]