Back to Blog

How to copy CPTs

import pyagrum as gum
import pyagrum.lib.notebook as gnb

Let say you have 2 Bayesian networks:

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"])
G A A B B A->B F F E E F->E C C C->B D D D->E
BN1
G A A B B A->B I I H H I->H G G G->H C C C->B
BN2

And you would like the CPTs of EE in BN1; and HH and BB in BN2 to be the same as BB in BN1. For now, they are (randomly) different :

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)"])
B
C
A
0
1
0
0
0.19870.8013
1
0.36360.6364
1
0
0.66870.3313
1
0.36640.6336

bn1.cpt(B)
E
F
D
0
1
0
0
0.05310.9469
1
0.62860.3714
1
0
0.60250.3975
1
0.77980.2202

bn1.cpt(E)
H
I
G
0
1
0
0
0.96560.0344
1
0.37270.6273
1
0
0.73100.2690
1
0.63820.3618

bn2.cpt(H)
B
A
C
0
1
0
0
0.00940.9906
1
0.46810.5319
1
0
0.33730.6627
1
0.61940.3806

bn2.cpt(B)

Even for BB 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).
# 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)"])
B
C
A
0
1
0
0
0.19870.8013
1
0.36360.6364
1
0
0.66870.3313
1
0.36640.6336

bn1.cpt(B)
E
F
D
0
1
0
0
0.19870.8013
1
0.36360.6364
1
0
0.66870.3313
1
0.36640.6336

bn1.cpt(E)
H
I
G
0
1
0
0
0.19870.8013
1
0.36360.6364
1
0
0.66870.3313
1
0.36640.6336

bn2.cpt(H)
B
A
C
0
1
0
0
0.19870.8013
1
0.66870.3313
1
0
0.36360.6364
1
0.36640.6336

bn2.cpt(B)