def test_bicgstab(self): diffusion = Diffusion(n_iter=-1) adjacency = test_digraph() scores1 = diffusion.fit_transform(adjacency, {0: 1}) scores2 = self.diffusion.fit_transform(adjacency, {0: 1}) self.assertAlmostEqual(0, np.linalg.norm(scores1 - scores2))
def __init__(self, n_iter: int = 10, damping_factor: Optional[float] = None, n_jobs: Optional[int] = None): algorithm = Diffusion(n_iter, damping_factor) super(DiffusionClassifier, self).__init__(algorithm, n_jobs) self._process_scores = process_scores
def fit(self, adjacency: Union[sparse.csr_matrix, np.ndarray], seeds: Union[np.ndarray, dict]) -> 'MultiDiff': """Compute multiple diffusions in a 1-vs-all mode. One class is the hot seeds while all the others are cold seeds. Parameters ---------- adjacency: Adjacency matrix of the graph. seeds: Dict or ndarray, If dict, ``(key, val)`` indicates that node ``key`` has label ``val``. If ndarray, ``seeds[i] = val`` indicates that node ``i`` has label ``val``. Negative values are treated has no label. Returns ------- self: :class:`MultiDiff` """ if isinstance(self, BiMultiDiff): diffusion = BiDiffusion(self.verbose, self.n_iter) else: diffusion = Diffusion(self.verbose, self.n_iter) seeds_labels = check_seeds(seeds, adjacency) classes, n_classes = check_labels(seeds_labels) n: int = adjacency.shape[0] personalizations = [] for label in classes: personalization = -np.ones(n) personalization[seeds_labels == label] = 1 ix = np.logical_and(seeds_labels != label, seeds_labels >= 0) personalization[ix] = 0 personalizations.append(personalization) if self.n_jobs != 1: local_function = partial(diffusion.fit_transform, adjacency) with Pool(self.n_jobs) as pool: membership = np.array( pool.map(local_function, personalizations)) membership = membership.T else: membership = np.zeros((n, n_classes)) for i in range(n_classes): membership[:, i] = diffusion.fit_transform( adjacency, personalization=personalizations[i])[:n] membership -= np.mean(membership, axis=0) membership = np.exp(membership) norms = membership.sum(axis=1) ix = np.argwhere(norms == 0).ravel() if len(ix) > 0: self.log.print('Nodes ', ix, ' have a null membership.') membership[~ix] /= norms[~ix, np.newaxis] self.membership_ = membership return self
def __init__(self, n_iter: int = 10, n_jobs: Optional[int] = None, verbose: bool = False): algorithm = Diffusion(n_iter, verbose) super(DiffusionClassifier, self).__init__(algorithm, n_jobs, verbose) self._process_seeds = process_seeds self._process_scores = process_scores
def test_damping_factor(self): for adjacency in [test_graph(), test_digraph()]: for algo in [ Diffusion(damping_factor=0.5), Dirichlet(damping_factor=0.5) ]: scores = algo.fit_transform(adjacency, {0: 0, 1: 1, 2: 0.5}) self.assertTrue(np.all(scores <= 1) and np.all(scores >= 0))
def test_range(self): for adjacency in [test_graph(), test_digraph()]: for algo in self.algos: scores = algo.fit_transform(adjacency, {0: 0, 1: 1, 2: 0.5}) self.assertTrue(np.all(scores <= 1) and np.all(scores >= 0)) biadjacency = test_bigraph() for algo in [Diffusion(), Dirichlet()]: scores = algo.fit_transform(biadjacency, seeds_row={0: 1}) self.assertTrue(np.all(scores <= 1) and np.all(scores >= 0)) scores = algo.fit_transform(biadjacency, seeds_row={0: 0.1}, seeds_col={1: 2}, init=0.3) self.assertTrue(np.all(scores <= 2) and np.all(scores >= 0.1))
def __init__(self, algo=None, damping_factor=0.85, solver='naive', n_iter=10, tol=0, undirected=False, method='exact'): if algo == 'diffusion': self.scorer = Diffusion(n_iter=n_iter) elif algo == 'closeness': self.scorer = Closeness(method=method, tol=tol) elif algo == 'harmonic': self.scorer = Harmonic() else: self.scorer = PageRank(damping_factor=damping_factor, solver=solver, n_iter=n_iter, tol=tol) self.undirected = undirected
class TestDiffusion(unittest.TestCase): def setUp(self): """Basic diffusion.""" self.diffusion = Diffusion() def test_unknown_types(self): with self.assertRaises(TypeError): # noinspection PyTypeChecker self.diffusion.fit(sparse.identity(2, format='csr'), seeds='test') def test_single_node_graph(self): self.diffusion.fit(sparse.identity(1, format='csr'), {0: 1}) self.assertEqual(self.diffusion.scores_, [1]) def test_range(self): for adjacency in [test_graph(), test_digraph()]: score = self.diffusion.fit_transform(adjacency, { 0: 0, 1: 1, 2: 0.5 }) self.assertTrue(np.all(score <= 1) and np.all(score >= 0)) bidiffusion = BiDiffusion() biadjacency = test_bigraph() score = bidiffusion.fit_transform(biadjacency, {0: 1}) self.assertTrue(np.all(score <= 1) and np.all(score >= 0)) def test_bicgstab(self): diffusion = Diffusion(n_iter=-1) adjacency = test_digraph() scores1 = diffusion.fit_transform(adjacency, {0: 1}) scores2 = self.diffusion.fit_transform(adjacency, {0: 1}) self.assertAlmostEqual(0, np.linalg.norm(scores1 - scores2))
def setUp(self): """Basic diffusion.""" self.diffusion = Diffusion()
def test_n_iter(self): with self.assertRaises(ValueError): Diffusion(n_iter=-1)
def setUp(self): self.algos = [Diffusion(), Dirichlet()]