Skip to content

Instantly share code, notes, and snippets.

@indapa
Created October 3, 2012 16:00
Show Gist options
  • Save indapa/3827801 to your computer and use it in GitHub Desktop.
Save indapa/3827801 to your computer and use it in GitHub Desktop.
Factor product example for a graphical model
#!/usr/bin/env python
import numpy as np
from Factor import *
from FactorOperations import *
#example from figure 4.3 in Koller and Friedman textbook, 'Probabilistic Graphical Models: Principles and Techniques'
a1=Factor([ 1, 2], [ 3, 2], [ 0, 0, 0, 0, 0, 0, 0, 0 ] )
b1=Factor( [2,3], [2,2], [ 0,0] )
assignmentA=IndexToAssignment( np.arange(0, np.prod( a1.getCard() )), a1.getCard() )
assignmentB=IndexToAssignment( np.arange(0, np.prod( b1.getCard() )), b1.getCard() )
#print assignmentA
#print assignmentB
valuesA=[.5,.1,.3,.8,0,.9]
valuesB=[.5,.1,.7,.2]
SetValueOfAssignment(a1,assignmentA,valuesA)
SetValueOfAssignment(b1,assignmentB,valuesB)
c1=FactorProduct(a1,b1)
assignmentC=IndexToAssignment(np.arange(0,np.prod( c1.getCard() )), c1.getCard() )
Ic1=AssignmentToIndex(assignmentC, c1.getCard() )
print assignmentC
print GetValueOfAssignment(c1,assignmentC)
#output
#[[ 1. 1. 1.]
# [ 2. 1. 1.]
# [ 3. 1. 1.]
# [ 1. 2. 1.]
# [ 2. 2. 1.]
# [ 3. 2. 1.]
# [ 1. 1. 2.]
# [ 2. 1. 2.]
# [ 3. 1. 2.]
# [ 1. 2. 2.]
# [ 2. 2. 2.]
# [ 3. 2. 2.]]
#[[ 0.25 0.05 0.15 0.08 0. 0.09 0.35 0.07 0.21 0.16 0. 0.18]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment