示例#1
0
def test_compute_affinity_matrix_args(almost_equal_decimals=5):
    """ test the compute_affinity_matrix parameter arguments """
    input_types = ['data', 'adjacency', 'affinity']
    params = [{'radius': 4}, {'radius': 5}]
    adjacency_method = 'auto'
    for affinity_method in affinity_methods():
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, affinity_method, **params[1])
        for init_params in params:
            for kwarg_params in params:
                true_params = init_params.copy()
                true_params.update(kwarg_params)
                affinity_true = compute_affinity_matrix(
                    D, adjacency_method, **true_params)
                for input in input_types:
                    G = Geometry(adjacency_method=adjacency_method,
                                 adjacency_kwds=params[1],
                                 affinity_method=affinity_method,
                                 affinity_kwds=init_params)
                    if input in ['data', 'adjacency']:
                        if input in ['data']:
                            G.set_data_matrix(X)
                        else:
                            G.set_adjacency_matrix(D)
                        affinity_queried = G.compute_affinity_matrix(
                            **kwarg_params)
                        assert_array_almost_equal(affinity_true.todense(),
                                                  affinity_queried.todense(),
                                                  almost_equal_decimals)
                    else:
                        G.set_affinity_matrix(A)
                        msg = distance_error_msg
                        assert_raise_message(ValueError, msg,
                                             G.compute_affinity_matrix)
示例#2
0
def test_compute_affinity_matrix_args(almost_equal_decimals=5):
    """ test the compute_affinity_matrix parameter arguments """
    input_types = ['data', 'adjacency', 'affinity']
    params = [{'radius':4}, {'radius':5}]
    adjacency_method = 'auto'
    for affinity_method in affinity_methods():
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, affinity_method, **params[1])
        for init_params in params:
            for kwarg_params in params:
                true_params = init_params.copy()
                true_params.update(kwarg_params)
                affinity_true = compute_affinity_matrix(D, adjacency_method,
                                                        **true_params)
                for input in input_types:
                    G = Geometry(adjacency_method = adjacency_method,
                                 adjacency_kwds = params[1],
                                 affinity_method = affinity_method,
                                 affinity_kwds = init_params)
                    if input in ['data', 'adjacency']:
                        if input in ['data']:
                            G.set_data_matrix(X)
                        else:
                            G.set_adjacency_matrix(D)
                        affinity_queried = G.compute_affinity_matrix(**kwarg_params)
                        assert_array_almost_equal(affinity_true.todense(), affinity_queried.todense(), almost_equal_decimals)
                    else:
                        G.set_affinity_matrix(A)
                        msg = distance_error_msg
                        assert_raise_message(ValueError, msg, G.compute_affinity_matrix)
示例#3
0
def test_affinity_vs_matlab():
    """Test that the affinity calculation matches the matlab result"""
    matlab = io.loadmat(TEST_DATA)

    D = np.sqrt(matlab['S'])  # matlab outputs squared distances
    A_matlab = matlab['A']
    radius = matlab['rad'][0]

    # check dense affinity computation
    A_dense = compute_affinity_matrix(D, radius=radius)
    assert_allclose(A_dense, A_matlab)

    # check sparse affinity computation
    A_sparse = compute_affinity_matrix(csr_matrix(D), radius=radius)
    assert_allclose(A_sparse.toarray(), A_matlab)
示例#4
0
def test_compute_laplacian_matrix_args(almost_equal_decimals=5):
    input_types = ['data', 'adjacency', 'affinity']
    params = [{}, {'radius': 4}, {'radius': 5}]
    lapl_params = [{}, {'scaling_epps': 4}, {'scaling_epps': 10}]
    adjacency_method = 'auto'
    affinity_method = 'auto'

    for laplacian_method in laplacian_methods():
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, affinity_method, **params[1])
        for init_params in lapl_params:
            for kwarg_params in lapl_params:
                true_params = init_params.copy()
                true_params.update(kwarg_params)
                laplacian_true = compute_laplacian_matrix(
                    A, laplacian_method, **true_params)
            for input in input_types:
                G = Geometry(adjacency_method=adjacency_method,
                             adjacency_kwds=params[1],
                             affinity_method=affinity_method,
                             affinity_kwds=params[1],
                             laplacian_method=laplacian_method,
                             laplacian_kwds=lapl_params[0])
                if input in ['data']:
                    G.set_data_matrix(X)
                if input in ['adjacency']:
                    G.set_adjacency_matrix(D)
                else:
                    G.set_affinity_matrix(A)
                laplacian_queried = G.compute_laplacian_matrix(**kwarg_params)
                assert_array_almost_equal(laplacian_true.todense(),
                                          laplacian_queried.todense(),
                                          almost_equal_decimals)
示例#5
0
def test_compute_laplacian_matrix_args(almost_equal_decimals=5):
    input_types = ['data', 'adjacency', 'affinity']
    params = [{}, {'radius':4}, {'radius':5}]
    lapl_params = [{}, {'scaling_epps':4}, {'scaling_epps':10}]
    adjacency_method = 'auto'
    affinity_method = 'auto'

    for laplacian_method in laplacian_methods():
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, affinity_method, **params[1])
        for init_params in lapl_params:
            for kwarg_params in lapl_params:
                    true_params = init_params.copy()
                    true_params.update(kwarg_params)
                    laplacian_true = compute_laplacian_matrix(A, laplacian_method, **true_params)
            for input in input_types:
                G = Geometry(adjacency_method = adjacency_method,
                             adjacency_kwds = params[1],
                             affinity_method = affinity_method,
                             affinity_kwds = params[1],
                             laplacian_method = laplacian_method,
                             laplacian_kwds = lapl_params[0])
                if input in ['data']:
                    G.set_data_matrix(X)
                if input in ['adjacency']:
                    G.set_adjacency_matrix(D)
                else:
                    G.set_affinity_matrix(A)
                laplacian_queried = G.compute_laplacian_matrix(**kwarg_params)
                assert_array_almost_equal(laplacian_true.todense(), laplacian_queried.todense(), almost_equal_decimals)
示例#6
0
def test_compute_adjacency_matrix_args(almost_equal_decimals=5):
    """ test the compute_adjacency_matrix parameter arguments """
    input_types = ['data', 'adjacency', 'affinity']
    params = [{'radius':1}, {'radius':2}]
    for adjacency_method in adjacency_methods():
        if adjacency_method == 'pyflann':
            try:
                import pyflann as pyf
            except ImportError:
                raise SkipTest("pyflann not installed.")
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, radius=1)
        for init_params in params:
            for kwarg_params in params:
                true_params = init_params.copy()
                true_params.update(kwarg_params)
                adjacency_true = compute_adjacency_matrix(X, adjacency_method, **true_params)
                G = Geometry(adjacency_method=adjacency_method, adjacency_kwds=init_params)
                for input in input_types:
                    G = Geometry(adjacency_kwds = init_params)
                    if input in ['data']:
                        G.set_data_matrix(X)
                        adjacency_queried = G.compute_adjacency_matrix(**kwarg_params)
                        assert_allclose(adjacency_true.toarray(),
                                        adjacency_queried.toarray(), rtol=1E-5)
                    else:
                        if input in ['adjacency']:
                            G.set_adjacency_matrix(D)
                        else:
                            G.set_affinity_matrix(A)
                        msg = distance_error_msg
                        assert_raise_message(ValueError, msg, G.compute_adjacency_matrix)
示例#7
0
    def check_affinity(adjacency_radius, affinity_radius, symmetrize):
        adj = compute_adjacency_matrix(X, radius=adjacency_radius)
        aff = compute_affinity_matrix(adj, radius=affinity_radius,
                                      symmetrize=True)

        A = np.exp(-(D / affinity_radius) ** 2)
        A[D > adjacency_radius] = 0
        assert_allclose(aff.toarray(), A)
示例#8
0
    def check_symmetric(method, adjacency_radius, affinity_radius):
        adj = compute_adjacency_matrix(X, radius=adjacency_radius)
        aff = compute_affinity_matrix(adj, radius=affinity_radius)
        lap, lapsym, w = compute_laplacian_matrix(aff, method=method,
                                                  full_output=True)

        sym = w[:, np.newaxis] * (lap.toarray() + np.eye(*lap.shape))

        assert_allclose(lapsym.toarray(), sym)
示例#9
0
def test_affinity_sparse_vs_dense():
    """
    Test that A_sparse is the same as A_dense for a small A matrix
    """
    rad = 2.
    n_samples = 6
    X = np.arange(n_samples)
    X = X[ :,np.newaxis]
    X = np.concatenate((X,np.zeros((n_samples,1),dtype=float)),axis=1)
    X = np.asarray( X, order="C" )
    test_dist_matrix = compute_adjacency_matrix( X, method = 'auto', radius = rad )
    A_dense = compute_affinity_matrix(test_dist_matrix.toarray(), method = 'auto',
                                      radius = rad, symmetrize = False )
    A_sparse = compute_affinity_matrix(csr_matrix(test_dist_matrix),
                                       method = 'auto', radius = rad, symmetrize = False)
    A_spdense = A_sparse.toarray()
    A_spdense[ A_spdense == 0 ] = 1.
    assert_allclose(A_dense, A_spdense)
示例#10
0
    def check_symmetric(method, adjacency_radius, affinity_radius):
        adj = compute_adjacency_matrix(X, radius=adjacency_radius)
        aff = compute_affinity_matrix(adj, radius=affinity_radius)
        lap, lapsym, w = compute_laplacian_matrix(aff,
                                                  method=method,
                                                  full_output=True)

        sym = w[:, np.newaxis] * (lap.toarray() + np.eye(*lap.shape))

        assert_allclose(lapsym.toarray(), sym)
示例#11
0
 def check_laplacian(input_type, laplacian_method):
     kwargs = {'scaling_epps': radius}
     if laplacian_method == 'renormalized':
         kwargs['renormalization_exponent'] = 1.5
     adjacency = input_type(np.sqrt(matlab['S']))
     affinity = compute_affinity_matrix(adjacency, radius=radius)
     laplacian = compute_laplacian_matrix(affinity,
                                          method=laplacian_method,
                                          **kwargs)
     if input_type is csr_matrix:
         laplacian = laplacian.toarray()
     assert_allclose(laplacian, laplacians[laplacian_method])
示例#12
0
 def check_laplacian(input_type, laplacian_method):
     kwargs = {'scaling_epps': radius}
     if laplacian_method == 'renormalized':
         kwargs['renormalization_exponent'] = 1.5
     adjacency = input_type(np.sqrt(matlab['S']))
     affinity = compute_affinity_matrix(adjacency, radius=radius)
     laplacian = compute_laplacian_matrix(affinity,
                                          method=laplacian_method,
                                          **kwargs)
     if input_type is csr_matrix:
         laplacian = laplacian.toarray()
     assert_allclose(laplacian, laplacians[laplacian_method])
示例#13
0
def test_custom_affinity():
    class CustomAffinity(Affinity):
        name = "custom"
        def affinity_matrix(self, adjacency_matrix):
            return np.exp(-abs(adjacency_matrix.toarray()))

    rand = np.random.RandomState(42)
    X = rand.rand(10, 2)
    D = compute_adjacency_matrix(X, radius=10)
    A = compute_affinity_matrix(D, method='custom', radius=1)
    assert_allclose(A, np.exp(-abs(D.toarray())))

    Affinity._remove_from_registry("custom")
示例#14
0
def test_laplacian_smoketest():
    rand = np.random.RandomState(42)
    X = rand.rand(20, 2)
    adj = compute_adjacency_matrix(X, radius=0.5)
    aff = compute_affinity_matrix(adj, radius=0.1)

    def check_laplacian(method):
        lap = compute_laplacian_matrix(aff, method=method)

        assert isspmatrix(lap)
        assert_equal(lap.shape, (X.shape[0], X.shape[0]))

    for method in Laplacian.asymmetric_methods():
        yield check_laplacian, method
示例#15
0
def test_laplacian_smoketest():
    rand = np.random.RandomState(42)
    X = rand.rand(20, 2)
    adj = compute_adjacency_matrix(X, radius=0.5)
    aff = compute_affinity_matrix(adj, radius=0.1)

    def check_laplacian(method):
        lap = compute_laplacian_matrix(aff, method=method)

        assert isspmatrix(lap)
        assert_equal(lap.shape, (X.shape[0], X.shape[0]))

    for method in Laplacian.asymmetric_methods():
        yield check_laplacian, method
示例#16
0
def test_compute_adjacency_matrix_args(almost_equal_decimals=5):
    """ test the compute_adjacency_matrix parameter arguments """
    input_types = ['data', 'adjacency', 'affinity']
    params = [{'radius': 1}, {'radius': 2}]
    for adjacency_method in adjacency_methods():
        if adjacency_method == 'pyflann':
            try:
                import pyflann as pyf
            except ImportError:
                raise SkipTest("pyflann not installed.")
        X = np.random.uniform(size=(10, 2))
        D = compute_adjacency_matrix(X, adjacency_method, **params[1])
        A = compute_affinity_matrix(D, radius=1)
        for init_params in params:
            for kwarg_params in params:
                true_params = init_params.copy()
                true_params.update(kwarg_params)
                adjacency_true = compute_adjacency_matrix(
                    X, adjacency_method, **true_params)
                G = Geometry(adjacency_method=adjacency_method,
                             adjacency_kwds=init_params)
                for input in input_types:
                    G = Geometry(adjacency_kwds=init_params)
                    if input in ['data']:
                        G.set_data_matrix(X)
                        adjacency_queried = G.compute_adjacency_matrix(
                            **kwarg_params)
                        assert_allclose(adjacency_true.toarray(),
                                        adjacency_queried.toarray(),
                                        rtol=1E-5)
                    else:
                        if input in ['adjacency']:
                            G.set_adjacency_matrix(D)
                        else:
                            G.set_affinity_matrix(A)
                        msg = distance_error_msg
                        assert_raise_message(ValueError, msg,
                                             G.compute_adjacency_matrix)