def example_binary(): # generate trivial data x = np.ones((10, 12)) x[:, 6:] = -1 x_noisy = x + np.random.normal(0, 0.8, size=x.shape) x_thresh = x_noisy > .0 # create unaries unaries = x_noisy # as we convert to int, we need to multipy to get sensible values unaries = (10 * np.dstack([unaries, -unaries]).copy("C")).astype(np.int32) # create potts pairwise pairwise = -10 * np.eye(2, dtype=np.int32) # do simple cut result_qpbo = binary_grid(unaries, pairwise) #result_qpbo = alpha_expansion_grid(unaries, pairwise) #result_gc = cut_simple(unaries, pairwise) # use the gerneral graph algorithm # first, we construct the grid graph inds = np.arange(x.size).reshape(x.shape) horz = np.c_[inds[:, :-1].ravel(), inds[:, 1:].ravel()] vert = np.c_[inds[:-1, :].ravel(), inds[1:, :].ravel()] edges = np.vstack([horz, vert]).astype(np.int32) # we flatten the unaries result_graph = binary_graph(edges, unaries.reshape(-1, 2), pairwise) # plot results plt.subplot(231, title="original") plt.imshow(x, interpolation='nearest') plt.subplot(232, title="noisy version") plt.imshow(x_noisy, interpolation='nearest') plt.subplot(233, title="rounded to integers") plt.imshow(unaries[:, :, 0], interpolation='nearest') plt.subplot(234, title="thresholding result") plt.imshow(x_thresh, interpolation='nearest') plt.subplot(235, title="qpbo") plt.imshow(result_qpbo, interpolation='nearest') plt.subplot(236, title="qpbo graph") plt.imshow(result_graph.reshape(x.shape), interpolation='nearest') plt.show()
def inference(self, x, w): if w.shape != (self.size_psi,): raise ValueError("Got w of wrong shape. Expected %s, got %s" % (self.size_psi, w.shape)) self.inference_calls += 1 pairwise_flat = np.asarray(w[:-1]) unary = w[-1] pairwise_params = np.zeros((self.n_states, self.n_states)) pairwise_params[np.tri(self.n_states, k=-1, dtype=np.bool)] = pairwise_flat pairwise_params = pairwise_params + pairwise_params.T\ - np.diag(np.diag(pairwise_params)) unaries = (-1000 * unary * x).astype(np.int32) pairwise = (-1000 * pairwise_params).astype(np.int32) y = alpha_expansion_graph(self.edges, unaries, pairwise, random_seed=1) from pyqpbo import binary_graph y_ = binary_graph(self.edges, unaries, pairwise) if (y_ != y).any(): tracer() return y