예제 #1
0
def test_matrix_dist(fn, exponent):
    [xarr, yarr], [x, y] = noise_elements(fn, n=2)
    sparse_mat = _sparse_matrix(fn)
    sparse_mat_as_dense = np.asarray(sparse_mat.todense())
    dense_mat = _dense_matrix(fn)

    if exponent == 1.0:  # d(x, y)_{A,1} = ||A(x-y)||_1
        true_dist_sparse = np.linalg.norm(np.dot(sparse_mat_as_dense,
                                                 xarr - yarr),
                                          ord=exponent)
        true_dist_dense = np.linalg.norm(np.dot(dense_mat, xarr - yarr),
                                         ord=exponent)
    elif exponent == 2.0:  # d(x, y)_{A,2} = sqrt(<x-y, A(x-y)>)
        true_dist_sparse = np.sqrt(
            np.vdot(xarr - yarr, np.dot(sparse_mat_as_dense, xarr - yarr)))
        true_dist_dense = np.sqrt(
            np.vdot(xarr - yarr, np.dot(dense_mat, xarr - yarr)))
    elif exponent == float('inf'):  # d(x, y)_{A,inf} = ||A(x-y)||_inf
        true_dist_sparse = np.linalg.norm(sparse_mat_as_dense.dot(xarr - yarr),
                                          ord=exponent)
        true_dist_dense = np.linalg.norm(dense_mat.dot(xarr - yarr),
                                         ord=exponent)
    else:  # d(x, y)_{A,p} = ||A^{1/p} (x-y)||_p
        # Calculate matrix power
        eigval, eigvec = scipy.linalg.eigh(dense_mat)
        eigval **= 1.0 / exponent
        mat_pow = (eigval * eigvec).dot(eigvec.conj().T)
        true_dist_dense = np.linalg.norm(np.dot(mat_pow, xarr - yarr),
                                         ord=exponent)

    if exponent in (1.0, 2.0, float('inf')):
        w_sparse = NumpyFnMatrixWeighting(sparse_mat, exponent=exponent)
        assert almost_equal(w_sparse.dist(x, y), true_dist_sparse)

    w_dense = NumpyFnMatrixWeighting(dense_mat, exponent=exponent)
    assert almost_equal(w_dense.dist(x, y), true_dist_dense)

    # With free functions
    if exponent in (1.0, 2.0, float('inf')):
        w_sparse_dist = npy_weighted_dist(sparse_mat, exponent=exponent)
        assert almost_equal(w_sparse_dist(x, y), true_dist_sparse)

    w_dense_dist = npy_weighted_dist(dense_mat, exponent=exponent)
    assert almost_equal(w_dense_dist(x, y), true_dist_dense)
예제 #2
0
def test_matrix_dist_using_inner(fn):
    [xarr, yarr], [x, y] = noise_elements(fn, 2)
    mat = _dense_matrix(fn)

    w = NumpyFnMatrixWeighting(mat, dist_using_inner=True)

    true_dist = np.sqrt(np.vdot(xarr - yarr, np.dot(mat, xarr - yarr)))
    # Using 3 places (single precision default) since the result is always
    # double even if the underlying computation was only single precision
    assert almost_equal(w.dist(x, y), true_dist, places=3)

    # Only possible for exponent=2
    with pytest.raises(ValueError):
        NumpyFnMatrixWeighting(mat, exponent=1, dist_using_inner=True)

    # With free function
    w_dist = npy_weighted_dist(mat, use_inner=True)
    assert almost_equal(w_dist(x, y), true_dist)