Exemplo n.º 1
0
def test_tree_factor():
    n_nodes = 10
    rng = np.random.RandomState(0)
    g = PFactorGraph()
    arcs = [(h, m) for m in range(1, n_nodes) for h in range(n_nodes)
            if h != m]
    potentials = rng.uniform(0, 1, size=len(arcs))
    arc_vars = [g.create_binary_variable() for _ in arcs]

    for var, potential in zip(arc_vars, potentials):
        var.set_log_potential(potential)

    tree = PFactorTree()
    g.declare_factor(tree, arc_vars)
    tree.initialize(n_nodes, arcs)

    _, posteriors, _, _ = g.solve()
    chosen_arcs = [arc for arc, post in zip(arcs, posteriors)
                   if post > 0.99]

    # check that it's a tree
    selected_nodes = set(a for arc in chosen_arcs for a in arc)
    assert selected_nodes == set(range(n_nodes))

    marked = list(range(n_nodes))
    for h, t in chosen_arcs:
        assert marked[t] != marked[h]
        marked[t] = marked[h]
Exemplo n.º 2
0
            -(1 + binary_vars[i].get_id()))
    description += ' ' + str(num_nodes - lower_bound)
    description += '\n'

    # Write factor graph to file.
    f = open('example_budget.fg', 'w')
    f.write(str(sum(num_states)) + '\n')
    f.write(str(num_factors) + '\n')
    for i in range(num_nodes):
        for j in range(num_states[i]):
            f.write(str(multi_variables[i].get_log_potential(j)) + '\n')
    f.write(description)
    f.close()

    # Run AD3.
    value, posteriors, _, _ = pairwise_fg.solve(branch_and_bound=True)
    # Print solution.
    best_states = var_len_argmax(posteriors, num_states)
    print("Solution using DENSE and BUDGET factors:", best_states)

# 2) Build a factor graph using a GENERAL_TREE factor.
factor_graph = PFactorGraph()

flat_var_log_potentials = np.concatenate(var_log_potentials)

additional_log_potentials = []
num_current_states = num_states[0]
for i in range(1, num_nodes):
    p = parents[i]
    num_previous_states = num_states[p]
    num_current_states = num_states[i]
Exemplo n.º 3
0
factor = PFactorSequence()
factor_graph.declare_factor(factor, variables)

factor.initialize(num_states)
factor.set_additional_log_potentials(edge_log_potentials)

# Create a budget factor.
variables = []
for i in range(length):
    if counts_for_budget[i]:
        variables.append(multi_variables[i].get_state(1))

factor_graph.create_factor_budget(variables, budget)

# Run AD3.
_, posteriors, _, _ = factor_graph.solve()

# Print solution.
best_states = np.array(posteriors).reshape(-1, 2).argmax(axis=1)

print("Solution using SEQUENCE + BUDGET factors:", best_states)

# 2) Build a factor graph using a COMPRESSION_BUDGET factor.
compression_factor_graph = PFactorGraph()

variable_log_potentials = list(var_log_potentials)

additional_log_potentials = []
index = 0
for i in range(length + 1):
    if i == 0:
Exemplo n.º 4
0
potts_matrix = alpha * np.eye(num_states)
potts_potentials = potts_matrix.ravel().tolist()

for i, j in itertools.product(range(grid_size), repeat=2):
    if j > 0:
        # horizontal edge
        edge_variables = [multi_variables[i][j - 1], multi_variables[i][j]]
        factor_graph.create_factor_dense(edge_variables, potts_potentials)

    if i > 0:
        # vertical edge
        edge_variables = [multi_variables[i - 1][j], multi_variables[i][j]]
        factor_graph.create_factor_dense(edge_variables, potts_potentials)

tic = time()
value, marginals, edge_marginals, solver_status = factor_graph.solve()
toc = time()

res = np.array(marginals).reshape(grid_size, grid_size, num_states)

unary = np.argmax(random_grid, axis=-1)
out = np.argmax(res, axis=-1)
if plot:
    plt.matshow(unary, vmin=0, vmax=4)
    plt.title("Unary potentials")
    plt.matshow(out, vmin=0, vmax=4)
    plt.title("Result of inference with dense factors ({:.2f}s)".format(toc -
                                                                        tic))
else:
    print("unary potentials: \n", unary)
    print("result with dense factors: \n", out)
Exemplo n.º 5
0
        description += ' ' + str(-(1 + binary_vars[i].get_id()))
    description += ' ' + str(num_nodes - lower_bound)
    description += '\n'

    # Write factor graph to file.
    f = open('example_budget.fg', 'w')
    f.write(str(sum(num_states)) + '\n')
    f.write(str(num_factors) + '\n')
    for i in range(num_nodes):
        for j in range(num_states[i]):
            f.write(str(multi_variables[i].get_log_potential(j)) + '\n')
    f.write(description)
    f.close()

    # Run AD3.
    value, posteriors, _, _ = pairwise_fg.solve(branch_and_bound=True)
    # Print solution.
    best_states = var_len_argmax(posteriors, num_states)
    print("Solution using DENSE and BUDGET factors:", best_states)

# 2) Build a factor graph using a GENERAL_TREE factor.
factor_graph = PFactorGraph()

flat_var_log_potentials = np.concatenate(var_log_potentials)

additional_log_potentials = []
num_current_states = num_states[0]
for i in range(1, num_nodes):
    p = parents[i]
    num_previous_states = num_states[p]
    num_current_states = num_states[i]
Exemplo n.º 6
0
potts_matrix = alpha * np.eye(num_states)
potts_potentials = potts_matrix.ravel().tolist()

for i, j in itertools.product(range(grid_size), repeat=2):
    if j > 0:
        # horizontal edge
        edge_variables = [multi_variables[i][j - 1], multi_variables[i][j]]
        factor_graph.create_factor_dense(edge_variables, potts_potentials)

    if i > 0:
        # vertical edge
        edge_variables = [multi_variables[i - 1][j], multi_variables[i][j]]
        factor_graph.create_factor_dense(edge_variables, potts_potentials)

tic = time()
value, marginals, edge_marginals, solver_status = factor_graph.solve()
toc = time()

res = np.array(marginals).reshape(grid_size, grid_size, num_states)

unary = np.argmax(random_grid, axis=-1)
out = np.argmax(res, axis=-1)
if plot:
    plt.matshow(unary, vmin=0, vmax=4)
    plt.title("Unary potentials")
    plt.matshow(out, vmin=0, vmax=4)
    plt.title("Result of inference with dense factors ({:.2f}s)".format(
                toc - tic))
else:
    print("unary potentials: \n", unary)
    print("result with dense factors: \n", out)
Exemplo n.º 7
0
    var = multi_variables[i]
    parent = multi_variables[parents[i]]
    pairwise_fg.create_factor_dense([parent, var], edge_log_potentials[i - 1])

# If there are upper/lower bounds, add budget factors.
if upper_bound >= 0 or lower_bound >= 0:
    variables = [var.get_state(counting_state)
                 for var, flag in zip(multi_variables, counts_for_budget)
                 if flag]
    pairwise_fg.create_factor_budget(variables, budget=upper_bound)
    pairwise_fg.create_factor_budget(variables,
                                     budget=len(variables) - lower_bound,
                                     negated=[True for _ in variables])

# Run AD3.
value, posteriors, _, _ = pairwise_fg.solve(branch_and_bound=True)

best_states = np.array(posteriors).reshape(-1, 2).argmax(axis=1)
print("Solution using DENSE and BUDGET factors:", best_states)

# 2) Build a factor graph using a BINARY_TREE factor.
tree_fg = PFactorGraph()

variables = []
for i in range(num_nodes):
    var = tree_fg.create_binary_variable()
    var.set_log_potential(var_log_potentials[i])
    variables.append(var)

if upper_bound >= 0 or lower_bound >= 0:
    additionals = np.zeros(num_nodes + 1)