learning

cslearn.learning.all_stagings(cards: list[int], level, max_cvars: int = 1, poss_cvars=None)[source]

Returns a generator over all stagings at a given level of a CStree with given variable cardinalities.

Parameters:
  • cards (list[int]) – List of cardinalities of the variables. Should be at least of length level+1. E.g.: l=2, cards=[2,2,2,2]

  • level (int) – The level of the stage (visually, this is where the nodes are colored).

  • max_cvars (int, optional) – The maximum number of context variables . Defaults to 1. Max is 2.

  • poss_cvars (list, optional) – The possible context variables. Defaults to None, meaning no restrictions.

Raises:

NotImplementedError – Exception if max_cvars > 2.

Yields:

generator – generator over all stagings of a given level.

Examples

>>> import cslearn.learning as ctl
>>> cards = [2]*3
>>> stagings = ctl.all_stagings(cards, 1, max_cvars=2) # all stagings at level 1
>>> for i, staging in enumerate(stagings):
...     print("staging {}:".format(i))
...     for stage in staging:
...         print(stage)
staging 0:
[{0, 1}, {0, 1}]
staging 1:
[0, {0, 1}]
[1, {0, 1}]
staging 2:
[0, 0]
[0, 1]
[1, {0, 1}]
staging 3:
[0, {0, 1}]
[1, 0]
[1, 1]
staging 4:
[0, 0]
[0, 1]
[1, 0]
[1, 1]
staging 5:
[{0, 1}, 0]
[{0, 1}, 1]
staging 6:
[0, 0]
[1, 0]
[{0, 1}, 1]
staging 7:
[{0, 1}, 0]
[0, 1]
[1, 1]
cslearn.learning.causallearn_graph_to_dag(graph, labels, alg='pc')[source]

Convert a causallearn graph to a DAG adjacency matrix.

Handles both directed and undirected edges in the CPDAG returned by PC, GRaSP, or GES: directed edges are kept as-is; undirected edges are oriented via pgmpy.base.PDAG.

Parameters:
  • graph – A graph object returned by a causallearn algorithm (PC, GRaSP, or GES). The expected format depends on alg.

  • labels (list) – Variable labels in the same order as the graph nodes.

  • alg (str) – Which algorithm produced graph. One of "pc", "grasp", or "ges". Defaults to "pc".

Returns:

Adjacency matrix of the resulting DAG with variable labels as both row and column names. Entry [i, j] == 1 means there is an edge from variable i to variable j.

Return type:

pd.DataFrame

cslearn.learning.causallearn_graph_to_posscvars(graph, labels, alg='pc')[source]

This function merely converts a graph estimated by causallearn to a dictionary of possible context variables. The possible context variables are the parents of each node in the graph. These are used when calculating scores in cslearn.scoring.order_score_tables().

Parameters:
  • graph – A graph object returned by a causallearn algorithm (PC, GRaSP, or GES). The expected format depends on alg.

  • labels (list) – Variable labels in the same order as the graph nodes.

  • alg (str) – Which algorithm produced graph. One of "pc", "grasp", or "ges". Defaults to "pc".

Returns:

Mapping from each variable label to a list of its possible context variables (i.e. variables that could be parents or undirected neighbours in the CPDAG).

Return type:

dict

Examples

>>> import cslearn.learning as ctl
>>> import cslearn.cstree as ct
>>> from causallearn.search.ConstraintBased.PC import pc
>>> import numpy as np
>>> import random
>>> np.random.seed(1)
>>> random.seed(1)
>>>
>>> tree = ct.sample_cstree([2,2,2,2], max_cvars=1, prob_cvar=0.5, prop_nonsingleton=1)
>>> tree.sample_stage_parameters(1.0)
>>> df = tree.sample(500)
>>> pcgraph = pc(df[1:].values, 0.05, "chisq", node_names=df.columns)
>>> poss_cvars = ctl.causallearn_graph_to_posscvars(pcgraph, labels=df.columns)
>>> print("Possible context variables per variable:", poss_cvars)
Depth=1, working on node 3: 100%|██████████| 4/4 [00:00<00:00, 1357.27it/s]
Possible context variables per variable: {0: [], 1: [2, 3], 2: [1], 3: [1]}
cslearn.learning.find_optimal_cstree(data, max_cvars=1, alpha_tot=1, method='BDeu')[source]

Find the optimal CStree for the data by exhaustive order search.

Enumerates all p! variable orderings, scores each one, then finds the optimal staging for the best ordering. Feasible only for small p (≤ ~7). For larger p, use cslearn.cstree.CStree.fit(), which replaces exhaustive order search with Gibbs MCMC and optionally uses a GRaSP-derived CPDAG to constrain the parent sets.

Parameters:
  • data (pd.DataFrame) – Training data.

  • max_cvars (int, optional) – Maximum context-set size β. Defaults to 1.

  • alpha_tot (float, optional) – Total BDeu pseudo-count. Defaults to 1.

  • method (str, optional) – Scoring method. Defaults to "BDeu".

Returns:

The MAP CStree (structure only, no parameters estimated).

Return type:

CStree

Examples

>>> import cslearn.learning as ctl
>>> import cslearn.cstree as ct
>>> import numpy as np
>>> import random
>>> np.random.seed(1)
>>> random.seed(1)
>>> tree = ct.sample_cstree([2,2,2,2], max_cvars=1, prob_cvar=0.5, prop_nonsingleton=1)
>>> tree.sample_stage_parameters(1.0)
>>> df = tree.sample(500)
>>> opttree = ctl.find_optimal_cstree(df, max_cvars=2, alpha_tot=1.0, method="BDeu")
>>> opttree.to_df()
cslearn.learning.gibbs_order_sampler(iterations, score_table)[source]

Gibbs order sampler for the posterior distribution over variable orderings.

At each iteration a random variable is selected and relocated to a new position drawn from the conditional posterior given all other positions.

Parameters:
  • iterations (int) – Number of Gibbs iterations.

  • score_table (dict) – Pre-computed order score table from cslearn.scoring.order_score_tables(). Must contain keys "scores" and "poss_cvars".

Returns:

(orders, scores) — a list of sampled orderings (one per iteration plus the initial state) and a list of their log-posterior scores.

Return type:

tuple

Example

>>> import cslearn.learning as ctl
>>> import cslearn.cstree as ct
>>> import cslearn.scoring as sc
>>> import numpy as np
>>> import random
>>> np.random.seed(1)
>>> random.seed(1)
>>> tree = ct.sample_cstree([2,2,2,2], max_cvars=1, prob_cvar=0.5, prop_nonsingleton=1)
>>> tree.sample_stage_parameters(1.0)
>>> df = tree.sample(500)
>>> score_table, context_scores, _ = sc.order_score_tables(
...     df, max_cvars=2, alpha_tot=1.0, method="BDeu", poss_cvars=None)
>>> orders, scores = ctl.gibbs_order_sampler(5000, score_table)
cslearn.learning.n_stagings(cards: list[int], level: int, max_cvars: int = 1)[source]

Returns the number of possible stagings at a given level of a CStree with given variable cardinalities.

Parameters:
  • cards (list) – List of cardinalities of the variables.

  • level (int) – The level in the CStree.

  • max_cvars (int, optional) – The maximum number of context variables per variable. Defaults to 1.

Examples

>>> import cslearn.learning as ctl
>>> cards = [2]*4
>>> ctl.n_stagings(cards, 2, max_cvars=2)
28