Пример #1
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)
Пример #2
0
def test_energy():
    # make sure that energy as computed by ssvm is the same as by lp
    np.random.seed(0)
    found_fractional = False
    while not found_fractional:
        x = np.random.normal(size=(2, 2, 3))
        unary_params = np.ones(3)
        pairwise_params = np.random.normal() * np.eye(3)
        edges = _make_grid_edges(x)
        # check map inference
        inf_res, energy_lp = _inference_lp(
            x, unary_params, pairwise_params, edges=edges, relaxed=True, return_energy=True, exact=True
        )
        found_fractional = np.any(np.max(inf_res[0], axis=-1) != 1)
        energy_svm = compute_energy(x, inf_res, unary_params, pairwise_params, neighborhood=4)

        assert_almost_equal(energy_lp, -energy_svm)