from random import choice line = list(25* 'a') + list(25 * 'b') + list(50* 'c') x = choice(range(100)) line[x] #is the sampled value def prior_sample(bn): # X1,...,XN are the variables in bn, ordered # so that a node does not appear to the right of a descendent x = [] for Var in [X1,..., XN]: x.append(random sample from P-dist(Var|parents(Var) in x)) return x def rejection_sample(X,e,N,bn): # X is the query var; e is the set of evidence variables # with their values; N is the number of samples Cts - a vector of counts for each value of X, all initially 0 for j = 1 to N: y = prior_sample(bn) if y is consistent with e then: Cts[xi] += 1, where xi is the value of X in y return normalize(Cts) def normalize(lst): s = sum(lst) i = 0 while i < len(lst): lst[i] = lst[i] / s i += 1 return lst def likelihood_weighting(X,e,N,bn): # X is the query var; e is the set of evidence variables # with their values; N is the number of samples Cts - a vector of counts for each value of X, all initially 0 for j = 1 to N: y,w = weighted_sample(bn,e) Cts[xi] += w, where xi is the value of X in y return normalize(Cts) def weighted_sample(bn,e): w = 1 x = [e] #e.g., if e = {MC=T, JC=F}, # x = [MC=T,JC=F] # X1,...,XN are the variables in bn, ordered # so that a node does not appear to the right of a descendent for each variable Xi: if Xi is an evidence variable with value xi in e: w = w * P(Xi=xi|parents(Xi) in x) else: x.append(random sample from P-dist(Xi|parents(Xi))) return x,w