How to copy CPTs
Posted on Wed 21 February 2024 in notebooks
In [1]:
import pyAgrum as gum
import pyAgrum.lib.notebook as gnb
Let say you have 2 Bayesian networks:
In [2]:
bn1=gum.fastBN("A->B<-C;D->E<-F",2)
bn2=gum.fastBN("C->B<-A;G->H<-I",2)
gnb.sideBySide(bn1,bn2,captions=["BN1","BN2"])
And you would like the CPTs of $E$ in BN1; and $H$ and $B$ in BN2 to be the same as $B$ in BN1. For now, they are (randomly) different :
In [3]:
gnb.sideBySide(bn1.cpt("B"),bn1.cpt("E"),bn2.cpt("H"),bn2.cpt("B"),
captions=["bn1.cpt(B)","bn1.cpt(E)","bn2.cpt(H)","bn2.cpt(B)"])
Even for $B$ in BN2, this is not trivial :
- the variables are not the same even if they have the same names : they belong to 2 different BNs.
- Note also that the order of the CPT is not the same : the column C and A are reversed in bn1.cpt(B) and bn2.cpt(B).
In [4]:
# using the names to map variables
bn2.cpt("B").fillWith(bn1.cpt("B"))
# using the order in "E" to organize the mapping of variables (E<->B,D<->A,F<->C)
#print(bn1.cpt("E").names)
#('E', 'D', 'F')
bn1.cpt("E").fillWith(bn2.cpt("B"),["B","A","C"])
# being explicit about the mapping (I<->C,G<->A,H<->B)
bn2.cpt("H").fillWith(bn2.cpt("B"),{"I":"C",
"G":"A",
"H":"B"})
gnb.sideBySide(bn1.cpt("B"),bn1.cpt("E"),bn2.cpt("H"),bn2.cpt("B"),
captions=["bn1.cpt(B)","bn1.cpt(E)","bn2.cpt(H)","bn2.cpt(B)"])