def test_knn_graph_anisotropy(): k = 3 a = 13 n_pca = 20 anisotropy = 0.9 thresh = 1e-4 data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)] pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small) data_small_nu = pca.transform(data_small) pdx = squareform(pdist(data_small_nu, metric="euclidean")) knn_dist = np.partition(pdx, k, axis=1)[:, :k] epsilon = np.max(knn_dist, axis=1) weighted_pdx = (pdx.T / epsilon).T K = np.exp(-1 * weighted_pdx ** a) K[K < thresh] = 0 K = K + K.T K = np.divide(K, 2) d = K.sum(1) W = K / (np.outer(d, d) ** anisotropy) np.fill_diagonal(W, 0) G = pygsp.graphs.Graph(W) G2 = build_graph( data_small, n_pca=n_pca, thresh=thresh, decay=a, knn=k - 1, random_state=42, use_pygsp=True, anisotropy=anisotropy, ) assert isinstance(G2, graphtools.graphs.kNNGraph) assert G.N == G2.N np.testing.assert_allclose(G.dw, G2.dw, atol=1e-14, rtol=1e-14) np.testing.assert_allclose((G2.W - G.W).data, 0, atol=1e-14, rtol=1e-14)
def test_exact_graph_anisotropy(): k = 3 a = 13 n_pca = 20 anisotropy = 0.9 data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)] pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small) data_small_nu = pca.transform(data_small) pdx = squareform(pdist(data_small_nu, metric="euclidean")) knn_dist = np.partition(pdx, k, axis=1)[:, :k] epsilon = np.max(knn_dist, axis=1) weighted_pdx = (pdx.T / epsilon).T K = np.exp(-1 * weighted_pdx**a) K = K + K.T K = np.divide(K, 2) d = K.sum(1) W = K / (np.outer(d, d)**anisotropy) np.fill_diagonal(W, 0) G = pygsp.graphs.Graph(W) G2 = build_graph( data_small, thresh=0, n_pca=n_pca, decay=a, knn=k - 1, random_state=42, use_pygsp=True, anisotropy=anisotropy, ) assert isinstance(G2, graphtools.graphs.TraditionalGraph) assert G.N == G2.N np.testing.assert_equal(G.dw, G2.dw) assert (G2.W != G.W).sum() == 0 assert (G.W != G2.W).nnz == 0 with assert_raises_message(ValueError, "Expected 0 <= anisotropy <= 1. Got -1"): build_graph( data_small, thresh=0, n_pca=n_pca, decay=a, knn=k - 1, random_state=42, use_pygsp=True, anisotropy=-1, ) with assert_raises_message(ValueError, "Expected 0 <= anisotropy <= 1. Got 2"): build_graph( data_small, thresh=0, n_pca=n_pca, decay=a, knn=k - 1, random_state=42, use_pygsp=True, anisotropy=2, ) with assert_raises_message(ValueError, "Expected 0 <= anisotropy <= 1. Got invalid"): build_graph( data_small, thresh=0, n_pca=n_pca, decay=a, knn=k - 1, random_state=42, use_pygsp=True, anisotropy="invalid", )