Learning k-TBNs

pyagrum.ktbn.KTBNDatabaseGenerator samples trajectory CSV databases from a k-TBN, for learning experiments.

class pyagrum.ktbn.KTBNDatabaseGenerator(kdbn)

KTBNDatabaseGenerator generates a database of trajectories from a pyagrum.ktbn.KTBN, one CSV file per trajectory. Unlike a plain Bayesian network, a k-TBN describes a stochastic process, so its database is a set of trajectories rather than a flat table of i.i.d. rows: each CSV file has one column per base variable and T data rows, an atemporal variable keeping the same value across all T rows.

Sampling follows the same forward (ancestral) sampling principle as pyAgrum’s Bayesian-network database generator, but never unrolls the k-TBN: it keeps only the k-slice template and slides it forward in time, so memory stays independent of the number of trajectories and their length.

KTBNDatabaseGenerator(kdbn) -> KTBNDatabaseGenerator
Parameters:
  • kdbn (pyagrum.ktbn.KTBN) – the k-TBN to sample from (only its k-slice template is copied; the k-TBN itself is not retained)

Parameters:

kdbn (KTBN)

Example

import pyagrum as gum
import pyagrum.ktbn as ktbn

model = ktbn.KTBN.fromBN(gum.fastBN("X0->X1->Y1;Y0;C->X1"))
gen = ktbn.KTBNDatabaseGenerator(model)
gum.initRandom(42)
loglikelihoods = gen.drawSamples(10, 5, ".", "traj")  # 10 trajectories of length 5: traj1.csv ... traj10.csv
len(loglikelihoods)  # one log2-likelihood per trajectory
# 10
len(open("traj10.csv").readlines())  # a header and 5 time steps
# 6

Methods

drawSamples()

Generate trajectories, writing one CSV file per trajectory into dirPath.

nbVars()

setDiscretizedLabelModeInterval()

Set discretized-variable label rendering to the interval label, e.g. "[0;1[".

setDiscretizedLabelModeMedian()

Set discretized-variable label rendering to the (deterministic) interval median.

setDiscretizedLabelModeRandom()

Set discretized-variable label rendering to a uniform random draw within the interval (the default; each labelled export then differs).

Attributes

DiscretizedLabelMode_INTERVAL

int([x]) -> integer int(x, base=10) -> integer

DiscretizedLabelMode_MEDIAN

int([x]) -> integer int(x, base=10) -> integer

DiscretizedLabelMode_RANDOM

int([x]) -> integer int(x, base=10) -> integer

VarOrderMode_ANTI_TOPOLOGICAL

int([x]) -> integer int(x, base=10) -> integer

VarOrderMode_RANDOM

int([x]) -> integer int(x, base=10) -> integer

VarOrderMode_TOPOLOGICAL

int([x]) -> integer int(x, base=10) -> integer

pyagrum.ktbn.KTBNLearner learns a k-TBN’s structure and/or parameters from trajectory CSVs, at a fixed order k.

class pyagrum.ktbn.KTBNLearner(*args)

KTBNLearner learns a pyagrum.ktbn.KTBN (structure and/or parameters), at a fixed order k, from a set of trajectory CSV files (one file per trajectory, as produced by pyagrum.ktbn.KTBNDatabaseGenerator: one column per base variable, one row per time step).

Internally, k-TBN learning is reduced to three ordinary Bayesian-network learning problems, solved with the same score/algorithm/prior machinery as pyagrum.BNLearner, then glued back together: the transition table (sliding windows of width k) learns the repeating kernel; the initial table (the first k-1 time steps of each trajectory) learns the initial slices; the atemporal table (one row per trajectory) learns the arcs between atemporal variables. Temporal ordering and no-backward-arc constraints are applied automatically.

KTBNLearner(dirPath, csvBaseName, nbSamples, k, atemporalVars, missingSymbols=[‘?’], induceTypes=True, ignoreMissingSymbols=False) -> KTBNLearner

Structure-learning constructor with the temporal/atemporal classification supplied explicitly.

Parameters:
  • dirPath (str) – directory holding the trajectory CSV files

  • csvBaseName (str) – stem of each file name (1-based index and .csv appended, e.g. "traj" -> traj1.csv, traj2.csv, …)

  • nbSamples (int) – number of CSV files to read

  • k (int) – order of the k-TBN; must be >= 2

  • atemporalVars (set[str]) – base names of the atemporal (static) variables; every other name found in the CSV header is temporal. Must be an actual Python set (a list/tuple at this position instead selects the atemporal-inferring overload)

  • missingSymbols (list[str]) – symbols in the CSVs interpreted as missing values

  • induceTypes (bool) – retype all-numeric columns as integer/range/continuous instead of plain labels

  • ignoreMissingSymbols (bool) – drop a row carrying a missing symbol instead of refusing the whole database (see nbDroppedRows() for the bias this introduces)

KTBNLearner(dirPath, csvBaseName, nbSamples, k, missingSymbols=[‘?’], induceTypes=True, ignoreMissingSymbols=False) -> KTBNLearner

Same, with the temporal/atemporal classification inferred instead: a base variable is atemporal iff its value never changes across the rows of any single trajectory (a heuristic – prefer the explicit form when the classification is already known).

KTBNLearner(dirPath, csvBaseName, nbSamples, k, bn, atemporalVars=set(), missingSymbols=[‘?’], ignoreMissingSymbols=False) -> KTBNLearner

Variable-schema constructor: types and domains are supplied via a reference pyagrum.BayesNet (one node per base variable, bare names, arcs ignored) instead of inferred from the CSVs. Use this when a variable’s full domain is not guaranteed to appear in the trajectories (the other constructors read the domains from all of them), or to give the variable types.

Parameters:
  • bn (pyagrum.BayesNet) – a BayesNet with one node per base variable, providing the variable types and domains

Example

import pyagrum as gum
import pyagrum.ktbn as ktbn

gum.initRandom(42)
model = ktbn.KTBN.fromBN(gum.fastBN("X0->X1->Y1;Y0;C->X0"))
ktbn.KTBNDatabaseGenerator(model).drawSamples(50, 10, ".", "traj")  # traj1.csv ... traj50.csv
schema = gum.fastBN("X;Y;C")  # the variables and their domains
learner = ktbn.KTBNLearner(".", "traj", 50, 2, schema, {"C"})  # k=2, C atemporal (an actual set)
learner.useScoreBIC().useGreedyHillClimbing()
learned = learner.learnKTBN()
learned.k()
# 2
sorted(learned.temporalVarNames()), sorted(learned.atemporalVarNames())
# (['X', 'Y'], ['C'])

Scientific notes

KTBNLearner learns a pyagrum.ktbn.KTBN of a given order \(k \geq 2\) from trajectories (one file per trajectory, one row per time step). The likelihood of a k-TBN factorizes into the initial slices, the transition kernel and the atemporal variables, so that, as [1] does for the prior and transition networks of a 2-TBN, the three parts are learned independently, each as an ordinary Bayesian network learning problem solved by pyagrum.BNLearner with the chosen algorithm, score, prior and constraints (MIIC by default, key BNLearnerPreferredAlgo of the section learning of the configuration).

The three tables. From a trajectory of length \(L\):

  • the transition table holds the \(L-k+1\) sliding windows \((\mathbf{v}_t, \dots, \mathbf{v}_{t+k-1})\), with the atemporal values. The variables of the slices \(0, \dots, k-2\) and the atemporal ones are forced to be roots, so that only the arcs entering the slice \(k-1\) (the kernel) are learned; the counts are then exactly the sufficient statistics of the kernel, summed over all the time steps \(t \geq k-1\);

  • the initial table holds one row per trajectory: its first \(k-1\) time steps. Arcs going back in time are forbidden and the atemporal variables are roots;

  • the atemporal table holds one row per trajectory with the atemporal values; it is used only when there are at least two atemporal variables (otherwise their distribution comes from the initial table).

The three learned networks are then glued: the initial slices from the initial table, the kernel (arcs and CPTs of slice \(k-1\)) from the transition table, the atemporal arcs and CPTs from the atemporal table.

Atemporal variables. When they are not given, a variable is classified atemporal if its value never changes within any trajectory (it may differ between trajectories): a temporal variable that happens to be constant in every trajectory is taken for an atemporal one.

Implementation limit. The initial slices are learned from as many rows as there are trajectories: with a few long trajectories, the initial distribution is poorly estimated, whatever their length. The domains of the variables are read from the first trajectory (unless a Bayesian network gives them). With missing values, the rows (windows) holding one are dropped (ignoreMissingSymbols), which is unbiased only when the values are missing completely at random.

Methods

addForbiddenArc()

Forbid an arc from ever appearing in the learned structure.

addForbiddenArcAllSlices()

Forbid tailBase -> headBase at every causally-possible slice pair (every lag): tailBase can never be an ancestor of headBase in the learned k-TBN.

addForbiddenIntraSliceArc()

Forbid tailBase -> headBase at every intra-slice position (i.e. for every slice t, tailBase[t] -> headBase[t]).

addMandatoryArc()

Force an arc to be part of the learned structure.

addNoChildrenNode()

Declare a node as a leaf (forbid it from having any child).

addNoParentNode()

Declare a node as a root (forbid it from having any parent).

addPossibleEdge()

Add a candidate edge for MIIC: once at least one edge has been listed, only explicitly listed edges are explored by the structure search.

allowArcAdditions()

Allow or forbid arc additions during structure search.

allowArcDeletions()

Allow or forbid arc deletions during structure search.

allowArcReversals()

Allow or forbid arc reversals during structure search.

checkScorePriorCompatibility()

copyState()

Copy all score/algorithm/prior/constraint settings from another KTBNLearner (does not copy the database).

domainSize()

domainSizes()

eraseForbiddenArc()

Undo a previous addForbiddenArc(), same arguments.

eraseForbiddenArcAllSlices()

Undo a previous addForbiddenArcAllSlices(), same arguments.

eraseForbiddenIntraSliceArc()

Undo a previous addForbiddenIntraSliceArc(), same arguments.

eraseMandatoryArc()

Undo a previous addMandatoryArc(), same arguments.

eraseNoChildrenNode()

Undo a previous addNoChildrenNode(), same arguments.

eraseNoParentNode()

Undo a previous addNoParentNode(), same arguments.

erasePossibleEdge()

Undo a previous addPossibleEdge(), same arguments.

hasMissingValues()

isConstraintBased()

isIgnoringMissingSymbols()

isScoreBased()

k()

latentVariables()

learnKTBN()

Learn the k-TBN’s structure and CPTs.

learnParameters()

Learn only the CPTs, using the arc structure of an already-known k-TBN.

names()

nbCols()

nbDroppedRows()

Number of rows dropped from the internal databases because they carried a missing symbol.

nbRows()

nbSamples()

setMaxIndegree()

Cap the number of parents of any single node.

state()

toString()

useExtendedGreedyHillClimbing()

Use greedy hill-climbing extended with arc-reversal moves.

useFCI()

Use the constraint-based FCI algorithm for structure search.

useGreedyHillClimbing()

Use greedy hill-climbing for structure search.

useGreedyThickThinning()

Use greedy thick-thinning for structure search.

useLocalSearchWithTabuList()

Use local search with a tabu list.

useMDLCorrection()

Use the MDL correction for MIIC’s independence tests.

useMIIC()

Use the constraint-based MIIC algorithm for structure search.

useNMLCorrection()

Use the NML correction for MIIC’s independence tests.

useNoCorrection()

Disable correction for MIIC’s independence tests.

usePC()

Use the constraint-based PC algorithm for structure search.

useScoreAIC()

Use the AIC score for structure learning.

useScoreBD()

Use the BD score for structure learning.

useScoreBDeu()

Use the BDeu score for structure learning.

useScoreBIC()

Use the BIC score for structure learning.

useScoreLog2Likelihood()

Use the raw log2-likelihood score for structure learning.

useScorefNML()

Use the fNML score for structure learning.

useSmoothingPrior()

Use a Laplace/BDeu-style smoothing prior.

pyagrum.ktbn.KTBNAdaptiveLearner additionally selects the order k itself, by exploring every candidate in a range and keeping the best one according to a cross-k model-selection criterion.

class pyagrum.ktbn.KTBNAdaptiveLearner(*args)

KTBNAdaptiveLearner is the order-selecting counterpart of pyagrum.ktbn.KTBNLearner: instead of being given the order k, it explores every candidate k in [kMin, kMax] (kMin starts at 2 and is raised automatically by structural constraints naming a concrete slice), learns one k-TBN per candidate with an internal pyagrum.ktbn.KTBNLearner, and keeps the one with the best cross-k model-selection score (BIC by default).

It exposes the same configuration interface as KTBNLearner (score, algorithm, prior, structural constraints – see that class’s docstrings, valid here too), except settings are only recorded and replayed on each per-k learner at learnKTBN() time; a constraint whose slice does not fit a given candidate is silently skipped for that candidate only.

KTBNAdaptiveLearner(dirPath, csvBaseName, nbSamples, kMax, atemporalVars, missingSymbols=[‘?’], induceTypes=True) -> KTBNAdaptiveLearner
Parameters:
  • dirPath (str) – directory holding the trajectory CSV files

  • csvBaseName (str) – stem of each file name

  • nbSamples (int) – number of CSV files to read

  • kMax (int) – largest order to explore; must be >= 2

  • atemporalVars (set[str]) – base names of the atemporal variables (must be an actual Python set)

  • missingSymbols (list[str]) – symbols in the CSVs interpreted as missing values

  • induceTypes (bool) – retype all-numeric columns

KTBNAdaptiveLearner(dirPath, csvBaseName, nbSamples, kMax, missingSymbols=[‘?’], induceTypes=True) -> KTBNAdaptiveLearner

Same, with the atemporal classification inferred from the data instead of supplied explicitly (see the equivalent KTBNLearner constructor).

KTBNAdaptiveLearner(dirPath, csvBaseName, nbSamples, kMax, bn, atemporalVars=set(), missingSymbols=[‘?’]) -> KTBNAdaptiveLearner

Variable-schema constructor: types and domains supplied via a reference pyagrum.BayesNet instead of inferred from the CSVs (see the equivalent KTBNLearner constructor).

Example

import pyagrum as gum
import pyagrum.ktbn as ktbn

gum.initRandom(42)
model = ktbn.KTBN.fromBN(gum.fastBN("X0->X1->Y1;Y0;C->X0"))
ktbn.KTBNDatabaseGenerator(model).drawSamples(50, 10, ".", "traj")  # traj1.csv ... traj50.csv
schema = gum.fastBN("X;Y;C")  # the variables and their domains
learner = ktbn.KTBNAdaptiveLearner(".", "traj", 50, 4, schema, {"C"})  # k in [2, 4], C atemporal
learner.useScoreBIC().useGreedyHillClimbing()
learned = learner.learnKTBN()
[k for k, score in learner.scorePerCandidateK()]  # one cross-k score per candidate order
# [2, 3, 4]
learned.k() == learner.bestK()
# True

Scientific notes

KTBNAdaptiveLearner also selects the order \(k\) of the k-TBN: for every candidate \(k \in [k_{min}, k_{max}]\) (\(k_{min} = 2\), or \(s+1\) if a constraint names the slice \(s\)), it learns a k-TBN with pyagrum.ktbn.KTBNLearner and the recorded configuration, then keeps the candidate with the best order score. This outer score is distinct from the score used to learn each structure, and it is computed on the whole learned k-TBN, so that it can be compared across \(k\).

The likelihood. All the candidates are scored on the same data: every time step of every trajectory. For a candidate \(k\), the instance at time \(t\) of a temporal variable is scored with the CPT of the slice \(\min(t, k-1)\) of the template (initial CPTs, then the kernel), and the atemporal variables once per trajectory:

\[\log_2 L_k = \sum_{\text{trajectories}} \Big( \sum_{C} \log_2 P(c \mid \mathrm{pa}_C) + \sum_{t \geq 0} \sum_{V} \log_2 P_{\min(t,k-1)}(v_t \mid \mathrm{pa}_{V_t}) \Big).\]

The order scores (to maximize), with \(d_k\) the number of free parameters of the template (all its slices and atemporal variables: \((r_X - 1)\, q_X\) for a node with \(r_X\) values and \(q_X\) parent configurations) and \(N\) the total number of time steps of all the trajectories, the same for every candidate:

  • BIC [2] (default): \(\log_2 L_k - \frac{1}{2} d_k \log_2 N\);

  • AIC [3]: \(\log_2 L_k - d_k \log_2 e\), i.e. Akaike’s \(\ln L - d\) converted to bits;

  • fNML [4]: \(\log_2 L_k - \sum_X \sum_j \log_2 C(r_X, N_{Xj})\), the parametric complexity of a multinomial with \(r_X\) values over the \(N_{Xj}\) instances of each observed parent configuration \(j\) of each node of the template (as in the fNML score of pyagrum.BNLearner).

A larger \(k\) adds initial slices and lags, hence parameters: the penalty trades them against the gain in likelihood. On ties, the smallest \(k\) is kept.

Implementation limit. With ignoreMissingSymbols, an instance whose family has a missing value is not scored; a larger \(k\) drops more instances (its families span more time steps) while \(N\) is not changed, which raises its likelihood and biases the choice towards larger orders. Every trajectory must have at least \(k_{max}\) time steps.

Methods

addForbiddenArc()

Forbid an arc from ever appearing in the learned structure.

addForbiddenArcAllSlices()

Forbid tailBase -> headBase at every causally-possible slice pair (every lag): tailBase can never be an ancestor of headBase in the learned k-TBN.

addForbiddenIntraSliceArc()

Forbid tailBase -> headBase at every intra-slice position (i.e. for every slice t, tailBase[t] -> headBase[t]).

addForbiddenKernelArc()

Forbid an arc from tailBase, lag slices before the kernel, to headBase in the kernel: tailBase at slice k-1-lag -> headBase at slice k-1, for whichever k is selected.

addMandatoryArc()

Force an arc to be part of the learned structure.

addMandatoryKernelArc()

Force an arc from tailBase, lag slices before the kernel, to headBase in the kernel.

addNoChildrenNode()

Declare a node as a leaf (forbid it from having any child).

addNoParentNode()

Declare a node as a root (forbid it from having any parent).

addPossibleEdge()

Add a candidate edge for MIIC: once at least one edge has been listed, only explicitly listed edges are explored by the structure search.

allowArcAdditions()

Allow or forbid arc additions during structure search.

allowArcDeletions()

Allow or forbid arc deletions during structure search.

allowArcReversals()

Allow or forbid arc reversals during structure search.

bestK()

checkScorePriorCompatibility()

Data-free check: evaluates the recorded (score, prior) pair as pyagrum.ktbn.KTBNLearner would, so an incompatible combination can be caught before learnKTBN reads any trajectory.

eraseForbiddenArc()

Undo a previous addForbiddenArc(), same arguments.

eraseForbiddenArcAllSlices()

Undo a previous addForbiddenArcAllSlices(), same arguments.

eraseForbiddenIntraSliceArc()

Undo a previous addForbiddenIntraSliceArc(), same arguments.

eraseForbiddenKernelArc()

Undo a previous addForbiddenKernelArc(), same arguments.

eraseMandatoryArc()

Undo a previous addMandatoryArc(), same arguments.

eraseMandatoryKernelArc()

Undo a previous addMandatoryKernelArc(), same arguments.

eraseNoChildrenNode()

Undo a previous addNoChildrenNode(), same arguments.

eraseNoParentNode()

Undo a previous addNoParentNode(), same arguments.

erasePossibleEdge()

Undo a previous addPossibleEdge(), same arguments.

ignoreMissingSymbols()

Learn and score on the fully observed data only, dropping every row and scoring instance that carries a missing symbol.

isIgnoringMissingSymbols()

kMax()

latentVariables()

learnKTBN()

Learn the best k in [kMin, kMax] together with the structure and the CPTs: one internal pyagrum.ktbn.KTBNLearner is built and run per candidate, the recorded configuration is replayed on each, and the k-TBN with the best cross-k score is returned.

scorePerCandidateK()

setMaxIndegree()

Cap the number of parents of any single node.

state()

toString()

useExtendedGreedyHillClimbing()

Use greedy hill-climbing extended with arc-reversal moves.

useFCI()

Use the constraint-based FCI algorithm for structure search.

useGreedyHillClimbing()

Use greedy hill-climbing for structure search.

useGreedyThickThinning()

Use greedy thick-thinning for structure search.

useLocalSearchWithTabuList()

Use local search with a tabu list.

useMDLCorrection()

Use the MDL correction for MIIC’s independence tests.

useMIIC()

Use the constraint-based MIIC algorithm for structure search.

useNMLCorrection()

Use the NML correction for MIIC’s independence tests.

useNoCorrection()

Disable correction for MIIC’s independence tests.

useOrderScoreAIC()

Select the best k by AIC: a lighter, sample-size-independent complexity penalty than BIC.

useOrderScoreBIC()

Select the best k by BIC (the default): the candidate maximising log2-likelihood minus half the parameter count times log2(sample size).

useOrderScorefNML()

Select the best k by fNML (factorized Normalized Maximum Likelihood): a data-dependent penalty (unlike BIC/AIC), matching aGrUM’s ScorefNML.

usePC()

Use the constraint-based PC algorithm for structure search.

useScoreAIC()

Use the AIC score for structure learning.

useScoreBD()

Use the BD score for structure learning.

useScoreBDeu()

Use the BDeu score for structure learning.

useScoreBIC()

Use the BIC score for structure learning.

useScoreLog2Likelihood()

Use the raw log2-likelihood score for structure learning.

useScorefNML()

Use the fNML score for structure learning.

useSmoothingPrior()

Use a Laplace/BDeu-style smoothing prior.

Attributes

OrderScoreType_AIC

int([x]) -> integer int(x, base=10) -> integer

OrderScoreType_BIC

int([x]) -> integer int(x, base=10) -> integer

OrderScoreType_fNML

int([x]) -> integer int(x, base=10) -> integer