Exemple #1
0
def test_binary_crf_exhaustive_loss_augmented():
    # tests graph cut inference against brute force
    # on random data / weights
    np.random.seed(0)
    for i in xrange(50):
        # generate data and weights
        y = np.random.randint(2, size=(3, 3))
        x = np.random.uniform(-1, 1, size=(3, 3))
        x = np.dstack([-x, np.zeros_like(x)])
        w = np.random.uniform(-1, 1, size=5)
        crf = GridCRF()
        # check loss augmented map inference
        y_hat = crf.loss_augmented_inference(x, y, w)
        y_ex = exhausive_loss_augmented_inference_binary(crf, x, y, w)
        # print(y_hat)
        # print(y_ex)
        # print("++++++++++++++++++++++")
        assert_array_equal(y_hat, y_ex)
Exemple #2
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)