Conditional Linear Gaussian models
In [1]:
import pyagrum as gum
import pyagrum.lib.notebook as gnb
import pyagrum.lib.bn_vs_bn as gcm
import pyagrum.clg as gclg
import pyagrum.clg.notebook as gclgnb
Build a CLG model
From scratch
Suppose we want to build a CLG with these specifications \(A={\cal N}(5,1)\), \(B={\cal N}(4,3)\) and \(C=2.A+3.B+{\cal N}(3,2)\)
In [2]:
model = gclg.CLG()
model.add(gclg.GaussianVariable("A", 5, 1))
model.add(gclg.GaussianVariable("C", 3, 2))
model.add(gclg.GaussianVariable("B", 4, 3))
model.addArc("A", "C", 2)
model.addArc("B", "C", 3)
model
Out[2]:
From SEM (Structural Equation Model)
We can create a Conditional Linear Gaussian Bayesian networ(CLG model) using a SEM-like syntax.
A = 4.5 [0.3] means that the mean of the distribution for Gaussian random variable A is 4.5 and ist standard deviation is 0.3.
B = 3 + 0.8F [0.3] means that the mean of the distribution for the Gaussian random variable B is 3 and the standard deviation is 0.3.
pyagrum.CLG.SEM is a set of static methods to manipulate this kind of SEM.
In [3]:
sem2 = """
A=4.5 [0.3] # comments are allowed
F=7 [0.5]
B=3 + 1.2F [0.3]
C=9 + 2A + 1.5B [0.6]
D=9 + C + F[0.7]
E=9 + D [0.9]
"""
model2 = gclg.SEM.toclg(sem2)
In [4]:
gnb.show(model2)
One can of course build the SEM from a CLG using pyagrum.CLG.SEM.tosem :
In [5]:
gnb.flow.row(
model,
"<pre><div align='left'>" + gclg.SEM.tosem(model) + "</div></pre>",
captions=["the first CLG model", "the SEM from the CLG"],
)
Out[5]:
B=4[3] A=5[1] C=3+2A+3B[2]
And this SEM allows of course input/output format for CLG
In [6]:
gclg.SEM.saveCLG(model2, "out/model2.sem")
print("=== file content ===")
with open("out/model2.sem", "r") as file:
for line in file.readlines():
print(line, end="")
print("====================")
=== file content ===
F=7.0[0.5]
B=3.0+1.2F[0.3]
A=4.5[0.3]
C=9.0+2.0A+1.5B[0.6]
D=9.0+F+C[0.7]
E=9.0+D[0.9]
====================
In [7]:
model3 = gclg.SEM.loadCLG("out/model2.sem")
gnb.sideBySide(model2, model3, captions=["saved model", "loaded model"])
input/output with pickle for CLG
In [8]:
import pickle
with open("out/testCLG.pkl", "bw") as f:
pickle.dump(model3, f)
model3
Out[8]:
In [9]:
model.dag().sizeArcs()
Out[9]:
2
In [10]:
with open("out/testCLG.pkl", "br") as f:
copyModel3 = pickle.load(f)
copyModel3
Out[10]:
Exact or approximated Inference
Exact inference : Variable Elimination
Compute some posterior using difference exact inference
In [11]:
ie = gclg.CLGVariableElimination(model2)
ie.updateEvidence({"D": 3})
print(ie.posterior("A"))
print(ie.posterior("B"))
print(ie.posterior("C"))
print(ie.posterior("D"))
print(ie.posterior("E"))
print(ie.posterior("F"))
v = ie.posterior("E")
print(v)
print(f" - mean(E|D=3)={v.mu()}")
print(f" - stdev(E|D=3)={v.sigma()}")
A:1.9327650111193468[0.28353638852446156]
B:-2.5058561897702[0.41002992170553515]
C:3.9722757598220895[0.5657771474513671]
D:3[0]
E:12.0[0.9]
F:-2.9836916234247597[0.32358490464094586]
E:12.0[0.9]
- mean(E|D=3)=12.0
- stdev(E|D=3)=0.9
In [12]:
gnb.sideBySide(
model2,
gclgnb.getInference(model2, evs={"D": 3}, size="3!"),
gclgnb.getInference(model2, evs={"D": 3, "F": 1}),
captions=["The CLG", "First inference", "Second inference"],
)
Approximated inference : MonteCarlo Sampling
When the model is too complex for exact infernece, we can use forward sampling to generate 5000 samples from the original CLG model.
In [13]:
fs = gclg.ForwardSampling(model2)
fs.makeSample(5000).tocsv("./out/model2.csv")
We will use the generated database to do learning. But before, we can also compute posterior but without evidence :
In [14]:
ie = gclg.CLGVariableElimination(model2)
print("| 'Exact' inference | Results from sampling |")
print("|------------------------------------------|------------------------------------------|")
for i in model2.names():
print(f"| {str(ie.posterior(i)):40} | {str(gclg.GaussianVariable(i, fs.mean_sample(i), fs.stddev_sample(i))):40} |")
| 'Exact' inference | Results from sampling |
|------------------------------------------|------------------------------------------|
| A:4.499999999999998[0.3] | A:4.4904652267036695[0.2995829235979487] |
| F:7.000000000000008[0.5000000000000002] | F:6.997167466878176[0.495342982976439] |
| B:11.399999999999999[0.6708203932499367] | B:11.398431359690608[0.6706876944107665] |
| C:35.099999999999994[1.3162446581088183] | C:35.063503359120894[1.307903993456683] |
| D:51.10000000000002[1.8364367672206963] | D:51.06722303756057[1.8110239391602465] |
| E:60.100000000000016[2.0451161336217565] | E:60.03679887937816[2.018379554745833] |
Now with the generated database and the original model, we can calculate the log-likelihood of the model.
In [15]:
print("log-likelihood w.r.t orignal model : ", model2.logLikelihood("./out/model2.csv"))
log-likelihood w.r.t orignal model : -22162.642750555708
Learning a CLG from data
Use the generated database to do our RAvel Learning. This part needs some time to run.
In [16]:
# RAveL learning
learner = gclg.CLGLearner("./out/model2.csv")
We can get the learned_clg model with function learn_clg() which contains structure learning and parameter estimation.
In [17]:
learned_clg = learner.learnCLG()
gnb.sideBySide(model2, learned_clg, captions=["original CLG", "learned CLG"])
Compare the learned model’s structure with that of the original model’.
In [18]:
cmp = gcm.GraphicalBNComparator(model2.asDiscreteBN(), learned_clg.asDiscreteBN())
print(f"F-score(original_clg,learned_clg) : {cmp.scores()['fscore']}")
F-score(original_clg,learned_clg) : 0.8
Get the learned model’s parameters and compare them with the original model’s parameters using the SEM syntax.
In [19]:
gnb.flow.row(
"<pre><div align='left'>" + gclg.SEM.tosem(model2) + "</div></pre>",
"<pre><div align='left'>" + gclg.SEM.tosem(learned_clg) + "</div></pre>",
captions=["original sem", "learned sem"],
)
Out[19]:
F=7.0[0.5] B=3.0+1.2F[0.3] A=4.5[0.3] C=9.0+2.0A+1.5B[0.6] D=9.0+F+C[0.7] E=9.0+D[0.9]
E=60.03679887937816[2.0183795547458327] F=6.997167466878176[0.495342982976439] B=2.927117913336719+1.210677532937969F[0.3003017633986479] D=6.1738294988195435+1.077180477031938F+0.6222214049744762E[0.7159245321934964] A=4.4904652267036695[0.2995829235979487] C=2.1648065013850726+1.2043092837775686A+0.6663946445683586B+0.3895832414369866D[0.4664254411235448]
We can algo do parameter estimation only with function fitParameters() if we already have the structure of the model.
In [20]:
# We can copy the original CLG
copy_original = gclg.CLG(model2)
# RAveL learning again
RAveL_l = gclg.CLGLearner("./out/model2.csv")
# Fit the parameters of the copy clg
RAveL_l.fitParameters(copy_original)
copy_original
Out[20]:
Compare two CLG models
We first create two CLG from two SEMs.
In [21]:
# TWO DIFFERENT CLGs
# FIRST CLG
clg1 = gclg.SEM.toclg("""
# hyper parameters
A=4[1]
B=3[5]
C=-2[5]
#equations
D=A[.2] # D is a noisy version of A
E=1+D+2B [2]
F=E+C+B+E [0.001]
""")
# SECOND CLG
clg2 = gclg.SEM.toclg("""
# hyper parameters
A=4[1]
B=3+A[5]
C=-2+2B+A[5]
#equations
D=A[.2] # D is a noisy version of A
E=1+D+2B [2]
F=E+C [0.001]
""")
This cell shows how to have a quick view of the differences
In [22]:
gnb.flow.row(clg1, clg2, gcm.graphDiff(clg1, clg2), gcm.graphDiffLegend(), gcm.graphDiff(clg2, clg1))
Out[22]:
We compare the CLG models.
In [23]:
# We use the F-score to compare the two CLGs
cmp = gcm.GraphicalBNComparator(clg1.asDiscreteBN(), clg1.asDiscreteBN())
print(f"F-score(clg1,clg1) : {cmp.scores()['fscore']}")
cmp = gcm.GraphicalBNComparator(clg1.asDiscreteBN(), clg2.asDiscreteBN())
print(f"F-score(clg1,clg2) : {cmp.scores()['fscore']}")
F-score(clg1,clg1) : 1.0
F-score(clg1,clg2) : 0.7142857142857143
In [24]:
# The complete list of structural scores is :
print("score(clg1,clg2) :")
for score, val in cmp.scores().items():
print(f" - {score} : {val}")
score(clg1,clg2) :
- count : {'tp': 5, 'tn': 6, 'fp': 3, 'fn': 1}
- recall : 0.8333333333333334
- precision : 0.625
- fscore : 0.7142857142857143
- dist2opt : 0.41036907507483766
- sid : 3
Forward Sampling
In [25]:
# We create a simple CLG with 3 variables
clg = gclg.CLG()
# prog=« sigma=2;X=N(5);Y=N(3);Z=X+Y »
A = gclg.GaussianVariable(mu=2, sigma=1, name="A")
B = gclg.GaussianVariable(mu=1, sigma=2, name="B")
C = gclg.GaussianVariable(mu=2, sigma=3, name="C")
idA = clg.add(A)
idB = clg.add(B)
idC = clg.add(C)
clg.addArc(idA, idB, 1.5)
clg.addArc(idB, idC, 0.75)
# We can show it as a graph
original_clg = gclgnb.CLG2dot(clg)
original_clg
Out[25]:
In [26]:
fs = gclg.ForwardSampling(clg)
fs.makeSample(10)
Out[26]:
<pyagrum.clg.forwardSampling.ForwardSampling at 0x113ac5d10>
In [27]:
print("A's sample_variance: ", fs.variance_sample(0))
print("B's sample_variance: ", fs.variance_sample("B"))
print("C's sample_variance: ", fs.variance_sample(2))
A's sample_variance: 1.2212594560270227
B's sample_variance: 1.6125978949140944
C's sample_variance: 12.589116573107349
In [28]:
print("A's sample_mean: ", fs.mean_sample("A"))
print("B's sample_mean: ", fs.mean_sample("B"))
print("C's sample_mean: ", fs.mean_sample("C"))
A's sample_mean: 2.099135142401045
B's sample_mean: 4.2558612332898225
C's sample_mean: 5.259942923976099
In [29]:
fs.toarray()
Out[29]:
array([[ 1.01396701, 1.34052319, 1.83297546],
[ 3.18289583, 4.281095 , 5.83701673],
[ 2.61171513, 5.55219089, 8.8594128 ],
[ 2.15063779, 4.11672611, 7.94703093],
[ 1.30431578, 4.39914402, 3.94878297],
[ 4.10912197, 6.15942579, 10.4588471 ],
[ 1.49967469, 5.18997409, 5.30387397],
[ 0.07571217, 4.28440397, -2.73511149],
[ 2.75898601, 4.16254288, 6.19397113],
[ 2.28432504, 3.07258641, 4.95262963]])
In [30]:
# export to dataframe
fs.topandas()
Out[30]:
| A | B | C | |
|---|---|---|---|
| 0 | 1.013967 | 1.340523 | 1.832975 |
| 1 | 3.182896 | 4.281095 | 5.837017 |
| 2 | 2.611715 | 5.552191 | 8.859413 |
| 3 | 2.150638 | 4.116726 | 7.947031 |
| 4 | 1.304316 | 4.399144 | 3.948783 |
| 5 | 4.109122 | 6.159426 | 10.458847 |
| 6 | 1.499675 | 5.189974 | 5.303874 |
| 7 | 0.075712 | 4.284404 | -2.735111 |
| 8 | 2.758986 | 4.162543 | 6.193971 |
| 9 | 2.284325 | 3.072586 | 4.952630 |
In [31]:
# export to csv
fs.makeSample(10000)
fs.tocsv("./out/samples.csv")
PC-algorithm & Parameter Estimation
The module allows to investigale more deeply into the learning algorithm.
We first create a random CLG model with 5 variables.
In [32]:
# Create a new random CLG
clg = gclg.randomCLG(nb_variables=5, names="ABCDE")
# Display the CLG
print(clg)
A=4.991307182391992[1.6829615979936703]
B=3.8595176551530628+9.836620752353983A[1.7809387744364327]
C=2.8368358052512335+2.257436518157472B[5.267027278305633]
D=1.8355439525515962-5.418424266105164B+6.872659178560417C[2.842899712616348]
E=4.89235581733192-1.5558819832440385A-4.8561864338076C[8.10696265765624]
We then do the Forward Sampling and CLGLearner.
In [33]:
n = 20 # n is the selected values of MC number n in n-MCERA
K = 10000 # K is the list of selected values of number of samples
Delta = 0.05 # Delta is the FWER we want to control
# Sample generation
fs = gclg.ForwardSampling(clg)
fs.makeSample(K).tocsv("./out/clg.csv")
# Learning
RAveL_l = gclg.CLGLearner("./out/clg.csv", n_sample=n, fwer_delta=Delta)
We use the PC algorithme to learn the structure of the model.
In [34]:
# Use the PC algorithm to get the skeleton
C = RAveL_l.PC_algorithm(order=clg.nodes(), verbose=False)
print("The final skeleton is:\n", C)
The final skeleton is:
{0: {1, 4}, 1: set(), 2: {0}, 3: set(), 4: {1, 3}}
In [35]:
# Create a Mixedgraph to display the skeleton
RAveL_MixGraph = gum.MixedGraph()
# Add variables
for i in range(len(clg.names())):
RAveL_MixGraph.addNodeWithId(i)
RAveL_MixGraph.setName(i, clg.variable(i).name())
# Add arcs and edges
for father, kids in C.items():
for kid in kids:
if father in C[kid]:
RAveL_MixGraph.addEdge(father, kid)
else:
RAveL_MixGraph.addArc(father, kid)
RAveL_MixGraph
Out[35]:
In [36]:
# Create a BN with the same structure as the CLG
bn = clg.asDiscreteBN()
# Compare the result above with the EssentialGraph
Real_EssentialGraph = gum.EssentialGraph(bn)
Real_EssentialGraph
Out[36]:
In [37]:
# create a CLG from the skeleton of PC algorithm
clg_PC = gclg.CLG()
for node in clg.nodes():
clg_PC.add(clg.variable(node))
for father, kids in C.items():
for kid in kids:
clg_PC.addArc(father, kid)
# Compare the structure of the created CLG and the original CLG
print(f"F-score : {clg.structuralFScore(clg_PC)}")
F-score : 0.8000000000000002
We can also do the parameter learning.
In [38]:
id2mu, id2sigma, arc2coef = RAveL_l.estimate_parameters(C)
for node in clg.nodes():
print(f"Real Value: node {node} : mu = {clg.variable(node)._mu}, sigma = {clg.variable(node)._sigma}")
print(f"Estimation: node {node} : mu = {id2mu[node]}, sigma = {id2sigma[node]}")
for arc in clg.arcs():
print(f"Real Value: arc {arc} : coef = {clg.coefArc(*arc)}")
print(f"Estimation: arc {arc} : coef = {(arc2coef[arc] if arc in arc2coef else '-')}")
Real Value: node 0 : mu = 3.8595176551530628, sigma = 1.7809387744364327
Estimation: node 0 : mu = 3.922347807180955, sigma = 1.7954520731447485
Real Value: node 1 : mu = 1.8355439525515962, sigma = 2.842899712616348
Estimation: node 1 : mu = 1.9557498176387753, sigma = 2.8593271937088782
Real Value: node 2 : mu = 4.991307182391992, sigma = 1.6829615979936703
Estimation: node 2 : mu = 4.96765754879694, sigma = 1.6720541878197626
Real Value: node 3 : mu = 4.89235581733192, sigma = 8.10696265765624
Estimation: node 3 : mu = 5.2296903769682785, sigma = 8.033710692119824
Real Value: node 4 : mu = 2.8368358052512335, sigma = 5.267027278305633
Estimation: node 4 : mu = 2.6865209441783406, sigma = 5.236317667812801
Real Value: arc (0, 1) : coef = -5.418424266105164
Estimation: arc (0, 1) : coef = -5.407931058331672
Real Value: arc (2, 3) : coef = -1.5558819832440385
Estimation: arc (2, 3) : coef = -
Real Value: arc (0, 4) : coef = 2.257436518157472
Estimation: arc (0, 4) : coef = 2.259002128551343
Real Value: arc (4, 1) : coef = 6.872659178560417
Estimation: arc (4, 1) : coef = 6.867444341554718
Real Value: arc (4, 3) : coef = -4.8561864338076
Estimation: arc (4, 3) : coef = -4.921392123525543
Real Value: arc (2, 0) : coef = 9.836620752353983
Estimation: arc (2, 0) : coef = 9.825532215113325

