def test_continuous_y(): # for inference_method in ["lp", "ad3"]: for inference_method in ["lp"]: X, Y = toy.generate_blocks(n_samples=1) x, y = X[0], Y[0] w = np.array([1, 1, 0, -4, 0]) crf = GridCRF(inference_method=inference_method) psi = crf.psi(x, y) y_cont = np.zeros_like(x) gx, gy = np.indices(x.shape[:-1]) y_cont[gx, gy, y] = 1 # need to generate edge marginals vert = np.dot(y_cont[1:, :, :].reshape(-1, 2).T, y_cont[:-1, :, :].reshape(-1, 2)) # horizontal edges horz = np.dot(y_cont[:, 1:, :].reshape(-1, 2).T, y_cont[:, :-1, :].reshape(-1, 2)) pw = vert + horz psi_cont = crf.psi(x, (y_cont, pw)) assert_array_almost_equal(psi, psi_cont) const = find_constraint(crf, x, y, w, relaxed=False) const_cont = find_constraint(crf, x, y, w, relaxed=True) # dpsi and loss are equal: assert_array_almost_equal(const[1], const_cont[1]) assert_almost_equal(const[2], const_cont[2]) # returned y_hat is one-hot version of other assert_array_equal(const[0], np.argmax(const_cont[0][0], axis=-1)) # test loss: assert_equal(crf.loss(y, const[0]), crf.continuous_loss(y, const_cont[0][0]))
def test_loss_augmentation(): X, Y = toy.generate_blocks(n_samples=1) x, y = X[0], Y[0] w = np.array([1.0, 1.0, 0.0, -4.0, 0.0]) unary_params = w[:2] pairwise_flat = np.asarray(w[2:]) pairwise_params = np.zeros((2, 2)) pairwise_params[np.tri(2, dtype=np.bool)] = pairwise_flat pairwise_params = pairwise_params + pairwise_params.T - np.diag(np.diag(pairwise_params)) crf = GridCRF() x_loss_augmented = crf.loss_augment(x, y, w) y_hat = crf.inference(x_loss_augmented, w) # test that loss_augmented_inference does the same y_hat_2 = crf.loss_augmented_inference(x, y, w) assert_array_equal(y_hat_2, y_hat) energy = compute_energy(x, y_hat, unary_params, pairwise_params) energy_loss_augmented = compute_energy(x_loss_augmented, y_hat, unary_params, pairwise_params) assert_almost_equal(energy + crf.loss(y, y_hat), energy_loss_augmented) # with zero in w: unary_params[1] = 0 assert_raises(ValueError, crf.loss_augment, x, y, w)