예제 #1
0
    def createSimpleGraph(self):
        # create the orphaned nodes
        node_names = ['x1', 'x2', 'x3', 'x4']
        dims = [2, 3, 2, 2]

        # pad array just so that reference like x[1] later is easier to read
        x = [None] + [Variable(node_names[i], dims[i]) for i in range(4)]

        f3 = Factor('f3', np.array([0.2, 0.8]))
        f4 = Factor('f4', np.array([0.5, 0.5]))

        # first index is x3, second index is x4, third index is x2
        # looking at it like: arr[0][0][0]
        f234 = Factor('f234', np.array([
            [
                [0.3, 0.5, 0.2], [0.1, 0.1, 0.8]
            ], [
                [0.9, 0.05, 0.05], [0.2, 0.7, 0.1]
            ]
        ]))

        # first index is x2
        f12 = Factor('f12', np.array([[0.8, 0.2], [0.2, 0.8], [0.5, 0.5]]))

        # attach nodes to graph in right order (connections matching
        # factor's potential's dimensions order)
        g = FactorGraph(x[3], silent=False, debug=True)
        g.append('x3', f234)
        g.append('f234', x[4])
        g.append('f234', x[2])
        g.append('x2', f12)
        g.append('f12', x[1])
        g.append('x3', f3)
        g.append('x4', f4)

        print('yes')


        g.compute_marginals();
        g.observe('x1', 1);
        g.compute_marginals();

        g.nodes['x1'].marginal();


        return g
예제 #2
0
        temp1 = Variable(str(reviewer2id[reviewer1]), 2)
        temp2 = Variable(str(reviewer2id[reviewer2]), 2)
        common_prod = float(row[3])
        common_burst = float(row[4])
        dist = float(row[5])
        dist_fact_name = 'distf' + str(reviewer2id[reviewer1]) + '_' + str(
            reviewer2id[reviewer2])
        dist_factor = Factor(dist_fact_name,
                             np.array([[1 - dist, dist], [dist, 1 - dist]]))
        graph.add(dist_factor)
        graph.append(dist_fact_name, temp2)
        graph.append(dist_fact_name, temp1)
        print 'adding pair no:', i
        i += 1

num_of_reviewers = len(reviewer2id)
reviewers = list(reviewer2id.keys())
random.shuffle(reviewers)
reviewers = reviewers[:num_of_reviewers / 5]

for i in reviewers:
    graph.observe(str(reviewer2id[i]), 2)

graph.compute_marginals(max_iter=500, tolerance=1e-4)

with open('output.csv', 'w') as f:
    for i in xrange(num_of_reviewers):
        output = str(i) + ', ' + id2reviewer[i] + ', ' + str(
            graph.nodes[str(i)].marginal()[0])
        f.write(output + '\n')