Click here to hide/show the list of notebooks.
  pyAgrum on notebooks   pyAgrum jupyter
☰  ParametricEM 
pyAgrum 0.15.2   
Zipped notebooks   
generation: 2019-07-22 10:34  

Creative Commons License
This pyAgrum's notebook is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

In [1]:
import pyAgrum as gum
import pyAgrum.lib.notebook as gnb

from pyAgrum.lib._utils.oslike import head

import os
#the bases will be saved in "out/*.csv"
EMnomissing=os.path.join("out","EM_nomissing.csv")
EMmissing=os.path.join("out","EM_missing.csv")

generating data with missing values (at random)

In [2]:
src=gum.fastBN("A->B<-C->D->E<-B;D->F")
gum.generateCSV(src,EMnomissing,5000,random_order=False)
src
Out[2]:
G A A B B A->B E E B->E C C C->B D D C->D D->E F F D->F
In [5]:
import pandas as pd
import numpy as np

def add_missing(src,dst,proba):
  df=pd.read_csv(src)
  mask=np.random.choice([True, False], size=df.shape,p=[proba,1-proba])
  df.mask(mask).to_csv(dst,na_rep='?',index=False,float_format='%.0f')

gum.generateCSV(src,EMnomissing,5000,random_order=False)
add_missing(EMnomissing,EMmissing,proba=0.1)
In [6]:
print("No missing")
head(EMnomissing)
print("Missing")
head(EMmissing)
No missing
A,B,C,D,E,F
1,0,1,0,1,0
1,1,0,0,0,0
0,1,1,0,0,0
0,1,1,1,0,0
1,1,0,0,0,0
1,0,1,1,0,1
0,1,1,0,1,1
0,1,0,0,0,0
1,0,1,0,0,0

Missing
A,B,C,D,E,F
1,?,1,0,1,0
1,?,0,?,0,0
0,1,1,0,0,0
0,1,1,1,0,0
1,1,0,0,0,0
?,0,1,1,0,1
0,1,1,0,1,1
0,1,?,0,0,0
1,0,1,0,0,0

learning with missing data

In [7]:
learner = gum.BNLearner(EMmissing, ["?"])
print(f"Missing values in {EMmissing} : {learner.hasMissingValues()}")
Missing values in out/EM_missing.csv : True
In [8]:
# this will fail : missing data !
# learner.learnParameters(src.dag())
In [9]:
learner.useEM(1e-3)
learner.useAprioriSmoothing()
bn=learner.learnParameters(src.dag())
print(f"# iterations : {learner.nbrIterations()}")
gnb.sideBySide(gnb.getInference(src),gnb.getInference(bn))
# iterations : 4

learning with smaller error (and no smoothing)

In [10]:
learner = gum.BNLearner(EMmissing, ["?"])
learner.setVerbosity(True)
learner.useEM(1e-8)
bn2=learner.learnParameters(src.dag())
print(f"# iterations : {learner.nbrIterations()}")
gnb.sideBySide(gnb.getInference(src),gnb.getInference(bn2))
# iterations : 12
In [11]:
print(learner.history())
(0.10875544961484049, 0.00803530750134867, 0.0017686428090886769, 0.0004129704683935825, 0.00010012693672179236, 2.489109413125611e-05, 6.297780171940571e-06, 1.614761322219348e-06, 4.1848329223473835e-07, 1.0943803994418663e-07, 2.88443643660906e-08, 7.655080717677401e-09)
In [ ]: