scikit-network 0.33.3__cp312-cp312-macosx_10_13_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of scikit-network might be problematic. Click here for more details.

Files changed (228) hide show
  1. scikit_network-0.33.3.dist-info/METADATA +122 -0
  2. scikit_network-0.33.3.dist-info/RECORD +228 -0
  3. scikit_network-0.33.3.dist-info/WHEEL +6 -0
  4. scikit_network-0.33.3.dist-info/licenses/AUTHORS.rst +43 -0
  5. scikit_network-0.33.3.dist-info/licenses/LICENSE +34 -0
  6. scikit_network-0.33.3.dist-info/top_level.txt +1 -0
  7. sknetwork/__init__.py +21 -0
  8. sknetwork/base.py +67 -0
  9. sknetwork/classification/__init__.py +8 -0
  10. sknetwork/classification/base.py +142 -0
  11. sknetwork/classification/base_rank.py +133 -0
  12. sknetwork/classification/diffusion.py +134 -0
  13. sknetwork/classification/knn.py +139 -0
  14. sknetwork/classification/metrics.py +205 -0
  15. sknetwork/classification/pagerank.py +66 -0
  16. sknetwork/classification/propagation.py +152 -0
  17. sknetwork/classification/tests/__init__.py +1 -0
  18. sknetwork/classification/tests/test_API.py +30 -0
  19. sknetwork/classification/tests/test_diffusion.py +77 -0
  20. sknetwork/classification/tests/test_knn.py +23 -0
  21. sknetwork/classification/tests/test_metrics.py +53 -0
  22. sknetwork/classification/tests/test_pagerank.py +20 -0
  23. sknetwork/classification/tests/test_propagation.py +24 -0
  24. sknetwork/classification/vote.cpp +27581 -0
  25. sknetwork/classification/vote.cpython-312-darwin.so +0 -0
  26. sknetwork/classification/vote.pyx +56 -0
  27. sknetwork/clustering/__init__.py +8 -0
  28. sknetwork/clustering/base.py +172 -0
  29. sknetwork/clustering/kcenters.py +253 -0
  30. sknetwork/clustering/leiden.py +242 -0
  31. sknetwork/clustering/leiden_core.cpp +31572 -0
  32. sknetwork/clustering/leiden_core.cpython-312-darwin.so +0 -0
  33. sknetwork/clustering/leiden_core.pyx +124 -0
  34. sknetwork/clustering/louvain.py +286 -0
  35. sknetwork/clustering/louvain_core.cpp +31217 -0
  36. sknetwork/clustering/louvain_core.cpython-312-darwin.so +0 -0
  37. sknetwork/clustering/louvain_core.pyx +124 -0
  38. sknetwork/clustering/metrics.py +91 -0
  39. sknetwork/clustering/postprocess.py +66 -0
  40. sknetwork/clustering/propagation_clustering.py +104 -0
  41. sknetwork/clustering/tests/__init__.py +1 -0
  42. sknetwork/clustering/tests/test_API.py +38 -0
  43. sknetwork/clustering/tests/test_kcenters.py +60 -0
  44. sknetwork/clustering/tests/test_leiden.py +34 -0
  45. sknetwork/clustering/tests/test_louvain.py +135 -0
  46. sknetwork/clustering/tests/test_metrics.py +50 -0
  47. sknetwork/clustering/tests/test_postprocess.py +39 -0
  48. sknetwork/data/__init__.py +6 -0
  49. sknetwork/data/base.py +33 -0
  50. sknetwork/data/load.py +406 -0
  51. sknetwork/data/models.py +459 -0
  52. sknetwork/data/parse.py +644 -0
  53. sknetwork/data/test_graphs.py +84 -0
  54. sknetwork/data/tests/__init__.py +1 -0
  55. sknetwork/data/tests/test_API.py +30 -0
  56. sknetwork/data/tests/test_base.py +14 -0
  57. sknetwork/data/tests/test_load.py +95 -0
  58. sknetwork/data/tests/test_models.py +52 -0
  59. sknetwork/data/tests/test_parse.py +250 -0
  60. sknetwork/data/tests/test_test_graphs.py +29 -0
  61. sknetwork/data/tests/test_toy_graphs.py +68 -0
  62. sknetwork/data/timeout.py +38 -0
  63. sknetwork/data/toy_graphs.py +611 -0
  64. sknetwork/embedding/__init__.py +8 -0
  65. sknetwork/embedding/base.py +94 -0
  66. sknetwork/embedding/force_atlas.py +198 -0
  67. sknetwork/embedding/louvain_embedding.py +148 -0
  68. sknetwork/embedding/random_projection.py +135 -0
  69. sknetwork/embedding/spectral.py +141 -0
  70. sknetwork/embedding/spring.py +198 -0
  71. sknetwork/embedding/svd.py +359 -0
  72. sknetwork/embedding/tests/__init__.py +1 -0
  73. sknetwork/embedding/tests/test_API.py +49 -0
  74. sknetwork/embedding/tests/test_force_atlas.py +35 -0
  75. sknetwork/embedding/tests/test_louvain_embedding.py +33 -0
  76. sknetwork/embedding/tests/test_random_projection.py +28 -0
  77. sknetwork/embedding/tests/test_spectral.py +81 -0
  78. sknetwork/embedding/tests/test_spring.py +50 -0
  79. sknetwork/embedding/tests/test_svd.py +43 -0
  80. sknetwork/gnn/__init__.py +10 -0
  81. sknetwork/gnn/activation.py +117 -0
  82. sknetwork/gnn/base.py +181 -0
  83. sknetwork/gnn/base_activation.py +90 -0
  84. sknetwork/gnn/base_layer.py +109 -0
  85. sknetwork/gnn/gnn_classifier.py +305 -0
  86. sknetwork/gnn/layer.py +153 -0
  87. sknetwork/gnn/loss.py +180 -0
  88. sknetwork/gnn/neighbor_sampler.py +65 -0
  89. sknetwork/gnn/optimizer.py +164 -0
  90. sknetwork/gnn/tests/__init__.py +1 -0
  91. sknetwork/gnn/tests/test_activation.py +56 -0
  92. sknetwork/gnn/tests/test_base.py +75 -0
  93. sknetwork/gnn/tests/test_base_layer.py +37 -0
  94. sknetwork/gnn/tests/test_gnn_classifier.py +130 -0
  95. sknetwork/gnn/tests/test_layers.py +80 -0
  96. sknetwork/gnn/tests/test_loss.py +33 -0
  97. sknetwork/gnn/tests/test_neigh_sampler.py +23 -0
  98. sknetwork/gnn/tests/test_optimizer.py +43 -0
  99. sknetwork/gnn/tests/test_utils.py +41 -0
  100. sknetwork/gnn/utils.py +127 -0
  101. sknetwork/hierarchy/__init__.py +6 -0
  102. sknetwork/hierarchy/base.py +96 -0
  103. sknetwork/hierarchy/louvain_hierarchy.py +272 -0
  104. sknetwork/hierarchy/metrics.py +234 -0
  105. sknetwork/hierarchy/paris.cpp +37865 -0
  106. sknetwork/hierarchy/paris.cpython-312-darwin.so +0 -0
  107. sknetwork/hierarchy/paris.pyx +316 -0
  108. sknetwork/hierarchy/postprocess.py +350 -0
  109. sknetwork/hierarchy/tests/__init__.py +1 -0
  110. sknetwork/hierarchy/tests/test_API.py +24 -0
  111. sknetwork/hierarchy/tests/test_algos.py +34 -0
  112. sknetwork/hierarchy/tests/test_metrics.py +62 -0
  113. sknetwork/hierarchy/tests/test_postprocess.py +57 -0
  114. sknetwork/linalg/__init__.py +9 -0
  115. sknetwork/linalg/basics.py +37 -0
  116. sknetwork/linalg/diteration.cpp +27397 -0
  117. sknetwork/linalg/diteration.cpython-312-darwin.so +0 -0
  118. sknetwork/linalg/diteration.pyx +47 -0
  119. sknetwork/linalg/eig_solver.py +93 -0
  120. sknetwork/linalg/laplacian.py +15 -0
  121. sknetwork/linalg/normalizer.py +86 -0
  122. sknetwork/linalg/operators.py +225 -0
  123. sknetwork/linalg/polynome.py +76 -0
  124. sknetwork/linalg/ppr_solver.py +170 -0
  125. sknetwork/linalg/push.cpp +31069 -0
  126. sknetwork/linalg/push.cpython-312-darwin.so +0 -0
  127. sknetwork/linalg/push.pyx +71 -0
  128. sknetwork/linalg/sparse_lowrank.py +142 -0
  129. sknetwork/linalg/svd_solver.py +91 -0
  130. sknetwork/linalg/tests/__init__.py +1 -0
  131. sknetwork/linalg/tests/test_eig.py +44 -0
  132. sknetwork/linalg/tests/test_laplacian.py +18 -0
  133. sknetwork/linalg/tests/test_normalization.py +34 -0
  134. sknetwork/linalg/tests/test_operators.py +66 -0
  135. sknetwork/linalg/tests/test_polynome.py +38 -0
  136. sknetwork/linalg/tests/test_ppr.py +50 -0
  137. sknetwork/linalg/tests/test_sparse_lowrank.py +61 -0
  138. sknetwork/linalg/tests/test_svd.py +38 -0
  139. sknetwork/linkpred/__init__.py +2 -0
  140. sknetwork/linkpred/base.py +46 -0
  141. sknetwork/linkpred/nn.py +126 -0
  142. sknetwork/linkpred/tests/__init__.py +1 -0
  143. sknetwork/linkpred/tests/test_nn.py +27 -0
  144. sknetwork/log.py +19 -0
  145. sknetwork/path/__init__.py +5 -0
  146. sknetwork/path/dag.py +54 -0
  147. sknetwork/path/distances.py +98 -0
  148. sknetwork/path/search.py +31 -0
  149. sknetwork/path/shortest_path.py +61 -0
  150. sknetwork/path/tests/__init__.py +1 -0
  151. sknetwork/path/tests/test_dag.py +37 -0
  152. sknetwork/path/tests/test_distances.py +62 -0
  153. sknetwork/path/tests/test_search.py +40 -0
  154. sknetwork/path/tests/test_shortest_path.py +40 -0
  155. sknetwork/ranking/__init__.py +8 -0
  156. sknetwork/ranking/base.py +61 -0
  157. sknetwork/ranking/betweenness.cpp +9704 -0
  158. sknetwork/ranking/betweenness.cpython-312-darwin.so +0 -0
  159. sknetwork/ranking/betweenness.pyx +97 -0
  160. sknetwork/ranking/closeness.py +92 -0
  161. sknetwork/ranking/hits.py +94 -0
  162. sknetwork/ranking/katz.py +83 -0
  163. sknetwork/ranking/pagerank.py +110 -0
  164. sknetwork/ranking/postprocess.py +37 -0
  165. sknetwork/ranking/tests/__init__.py +1 -0
  166. sknetwork/ranking/tests/test_API.py +32 -0
  167. sknetwork/ranking/tests/test_betweenness.py +38 -0
  168. sknetwork/ranking/tests/test_closeness.py +30 -0
  169. sknetwork/ranking/tests/test_hits.py +20 -0
  170. sknetwork/ranking/tests/test_pagerank.py +62 -0
  171. sknetwork/ranking/tests/test_postprocess.py +26 -0
  172. sknetwork/regression/__init__.py +4 -0
  173. sknetwork/regression/base.py +61 -0
  174. sknetwork/regression/diffusion.py +210 -0
  175. sknetwork/regression/tests/__init__.py +1 -0
  176. sknetwork/regression/tests/test_API.py +32 -0
  177. sknetwork/regression/tests/test_diffusion.py +56 -0
  178. sknetwork/sknetwork.py +3 -0
  179. sknetwork/test_base.py +35 -0
  180. sknetwork/test_log.py +15 -0
  181. sknetwork/topology/__init__.py +8 -0
  182. sknetwork/topology/cliques.cpp +32562 -0
  183. sknetwork/topology/cliques.cpython-312-darwin.so +0 -0
  184. sknetwork/topology/cliques.pyx +149 -0
  185. sknetwork/topology/core.cpp +30648 -0
  186. sknetwork/topology/core.cpython-312-darwin.so +0 -0
  187. sknetwork/topology/core.pyx +90 -0
  188. sknetwork/topology/cycles.py +243 -0
  189. sknetwork/topology/minheap.cpp +27329 -0
  190. sknetwork/topology/minheap.cpython-312-darwin.so +0 -0
  191. sknetwork/topology/minheap.pxd +20 -0
  192. sknetwork/topology/minheap.pyx +109 -0
  193. sknetwork/topology/structure.py +194 -0
  194. sknetwork/topology/tests/__init__.py +1 -0
  195. sknetwork/topology/tests/test_cliques.py +28 -0
  196. sknetwork/topology/tests/test_core.py +19 -0
  197. sknetwork/topology/tests/test_cycles.py +65 -0
  198. sknetwork/topology/tests/test_structure.py +85 -0
  199. sknetwork/topology/tests/test_triangles.py +38 -0
  200. sknetwork/topology/tests/test_wl.py +72 -0
  201. sknetwork/topology/triangles.cpp +8891 -0
  202. sknetwork/topology/triangles.cpython-312-darwin.so +0 -0
  203. sknetwork/topology/triangles.pyx +151 -0
  204. sknetwork/topology/weisfeiler_lehman.py +133 -0
  205. sknetwork/topology/weisfeiler_lehman_core.cpp +27632 -0
  206. sknetwork/topology/weisfeiler_lehman_core.cpython-312-darwin.so +0 -0
  207. sknetwork/topology/weisfeiler_lehman_core.pyx +114 -0
  208. sknetwork/utils/__init__.py +7 -0
  209. sknetwork/utils/check.py +355 -0
  210. sknetwork/utils/format.py +221 -0
  211. sknetwork/utils/membership.py +82 -0
  212. sknetwork/utils/neighbors.py +115 -0
  213. sknetwork/utils/tests/__init__.py +1 -0
  214. sknetwork/utils/tests/test_check.py +190 -0
  215. sknetwork/utils/tests/test_format.py +63 -0
  216. sknetwork/utils/tests/test_membership.py +24 -0
  217. sknetwork/utils/tests/test_neighbors.py +41 -0
  218. sknetwork/utils/tests/test_tfidf.py +18 -0
  219. sknetwork/utils/tests/test_values.py +66 -0
  220. sknetwork/utils/tfidf.py +37 -0
  221. sknetwork/utils/values.py +76 -0
  222. sknetwork/visualization/__init__.py +4 -0
  223. sknetwork/visualization/colors.py +34 -0
  224. sknetwork/visualization/dendrograms.py +277 -0
  225. sknetwork/visualization/graphs.py +1039 -0
  226. sknetwork/visualization/tests/__init__.py +1 -0
  227. sknetwork/visualization/tests/test_dendrograms.py +53 -0
  228. sknetwork/visualization/tests/test_graphs.py +176 -0
@@ -0,0 +1,56 @@
1
+ # distutils: language = c++
2
+ # cython: language_level=3
3
+ """
4
+ Created in April 2020
5
+ @author: Nathan de Lara <nathan.delara@polytechnique.org>
6
+ """
7
+ from libcpp.set cimport set
8
+ from libcpp.vector cimport vector
9
+
10
+ cimport cython
11
+
12
+
13
+ @cython.boundscheck(False)
14
+ @cython.wraparound(False)
15
+ def vote_update(int[:] indptr, int[:] indices, float[:] data, int[:] labels, int[:] index):
16
+ """One pass of label updates over the graph by majority vote among neighbors."""
17
+ cdef int i
18
+ cdef int ii
19
+ cdef int j
20
+ cdef int jj
21
+ cdef int n_indices = index.shape[0]
22
+ cdef int label
23
+ cdef int label_neigh_size
24
+ cdef float best_score
25
+
26
+ cdef vector[int] labels_neigh
27
+ cdef vector[float] votes_neigh, votes
28
+ cdef set[int] labels_unique = ()
29
+
30
+ cdef int n = labels.shape[0]
31
+ for i in range(n):
32
+ votes.push_back(0)
33
+
34
+ for ii in range(n_indices):
35
+ i = index[ii]
36
+ labels_neigh.clear()
37
+ for j in range(indptr[i], indptr[i + 1]):
38
+ jj = indices[j]
39
+ labels_neigh.push_back(labels[jj])
40
+ votes_neigh.push_back(data[jj])
41
+
42
+ labels_unique.clear()
43
+ label_neigh_size = labels_neigh.size()
44
+ for jj in range(label_neigh_size):
45
+ label = labels_neigh[jj]
46
+ if label >= 0:
47
+ labels_unique.insert(label)
48
+ votes[label] += votes_neigh[jj]
49
+
50
+ best_score = -1
51
+ for label in labels_unique:
52
+ if votes[label] > best_score:
53
+ labels[i] = label
54
+ best_score = votes[label]
55
+ votes[label] = 0
56
+ return labels
@@ -0,0 +1,8 @@
1
+ """clustering module"""
2
+ from sknetwork.clustering.base import BaseClustering
3
+ from sknetwork.clustering.louvain import Louvain
4
+ from sknetwork.clustering.leiden import Leiden
5
+ from sknetwork.clustering.propagation_clustering import PropagationClustering
6
+ from sknetwork.clustering.metrics import get_modularity
7
+ from sknetwork.clustering.postprocess import reindex_labels, aggregate_graph
8
+ from sknetwork.clustering.kcenters import KCenters
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Nov, 2019
5
+ @author: Nathan de Lara <nathan.delara@polytechnique.org>
6
+ """
7
+ from abc import ABC
8
+
9
+ import numpy as np
10
+ from scipy import sparse
11
+
12
+ from sknetwork.linalg.normalizer import normalize
13
+ from sknetwork.base import Algorithm
14
+ from sknetwork.utils.membership import get_membership
15
+
16
+
17
+ class BaseClustering(Algorithm, ABC):
18
+ """Base class for clustering algorithms.
19
+
20
+ Attributes
21
+ ----------
22
+ labels_ : np.ndarray, shape (n_labels,)
23
+ Label of each node.
24
+ probs_ : sparse.csr_matrix, shape (n_row, n_labels)
25
+ Probability distribution over labels.
26
+ labels_row_, labels_col_ : np.ndarray
27
+ Labels of rows and columns, for bipartite graphs.
28
+ probs_row_, probs_col_ : sparse.csr_matrix, shape (n_row, n_labels)
29
+ Probability distributions over labels for rows and columns (for bipartite graphs).
30
+ aggregate_ : sparse.csr_matrix
31
+ Aggregate adjacency matrix or biadjacency matrix between clusters.
32
+ """
33
+ def __init__(self, sort_clusters: bool = True, return_probs: bool = False, return_aggregate: bool = False):
34
+ self.sort_clusters = sort_clusters
35
+ self.return_probs = return_probs
36
+ self.return_aggregate = return_aggregate
37
+ self._init_vars()
38
+
39
+ def predict(self, columns=False) -> np.ndarray:
40
+ """Return the labels predicted by the algorithm.
41
+
42
+ Parameters
43
+ ----------
44
+ columns : bool
45
+ If ``True``, return the prediction for columns.
46
+
47
+ Returns
48
+ -------
49
+ labels : np.ndarray
50
+ Labels.
51
+ """
52
+ if columns:
53
+ return self.labels_col_
54
+ return self.labels_
55
+
56
+ def fit_predict(self, *args, **kwargs) -> np.ndarray:
57
+ """Fit algorithm to the data and return the labels. Same parameters as the ``fit`` method.
58
+
59
+ Returns
60
+ -------
61
+ labels : np.ndarray
62
+ Labels.
63
+ """
64
+ self.fit(*args, **kwargs)
65
+ return self.predict()
66
+
67
+ def predict_proba(self, columns=False) -> np.ndarray:
68
+ """Return the probability distribution over labels as predicted by the algorithm.
69
+
70
+ Parameters
71
+ ----------
72
+ columns : bool
73
+ If ``True``, return the prediction for columns.
74
+
75
+ Returns
76
+ -------
77
+ probs : np.ndarray
78
+ Probability distribution over labels.
79
+ """
80
+ if columns:
81
+ return self.probs_col_.toarray()
82
+ return self.probs_.toarray()
83
+
84
+ def fit_predict_proba(self, *args, **kwargs) -> np.ndarray:
85
+ """Fit algorithm to the data and return the probability distribution over labels.
86
+ Same parameters as the ``fit`` method.
87
+
88
+ Returns
89
+ -------
90
+ probs : np.ndarray
91
+ Probability of each label.
92
+ """
93
+ self.fit(*args, **kwargs)
94
+ return self.predict_proba()
95
+
96
+ def transform(self, columns=False) -> sparse.csr_matrix:
97
+ """Return the probability distribution over labels in sparse format.
98
+
99
+ Parameters
100
+ ----------
101
+ columns : bool
102
+ If ``True``, return the prediction for columns.
103
+
104
+ Returns
105
+ -------
106
+ probs : sparse.csr_matrix
107
+ Probability distribution over labels.
108
+ """
109
+ if columns:
110
+ return self.probs_col_
111
+ return self.probs_
112
+
113
+ def fit_transform(self, *args, **kwargs) -> np.ndarray:
114
+ """Fit algorithm to the data and return the membership matrix. Same parameters as the ``fit`` method.
115
+
116
+ Returns
117
+ -------
118
+ membership : np.ndarray
119
+ Membership matrix (distribution over clusters).
120
+ """
121
+ self.fit(*args, **kwargs)
122
+ return self.transform()
123
+
124
+ def _init_vars(self):
125
+ """Init variables."""
126
+ self.labels_ = None
127
+ self.labels_row_ = None
128
+ self.labels_col_ = None
129
+ self.probs_ = None
130
+ self.probs_row_ = None
131
+ self.probs_col_ = None
132
+ self.aggregate_ = None
133
+ self.bipartite = None
134
+ return self
135
+
136
+ def _split_vars(self, shape):
137
+ """Split labels_ into labels_row_ and labels_col_"""
138
+ n_row = shape[0]
139
+ self.labels_row_ = self.labels_[:n_row]
140
+ self.labels_col_ = self.labels_[n_row:]
141
+ self.labels_ = self.labels_row_
142
+ return self
143
+
144
+ def _secondary_outputs(self, input_matrix: sparse.csr_matrix):
145
+ """Compute different variables from labels_."""
146
+ if self.return_probs or self.return_aggregate:
147
+ input_matrix = input_matrix.astype(float)
148
+ if not self.bipartite:
149
+ probs = get_membership(self.labels_)
150
+ if self.return_probs:
151
+ self.probs_ = normalize(input_matrix.dot(probs))
152
+ if self.return_aggregate:
153
+ self.aggregate_ = sparse.csr_matrix(probs.T.dot(input_matrix.dot(probs)))
154
+ else:
155
+ if self.labels_col_ is None:
156
+ n_labels = max(self.labels_) + 1
157
+ probs_row = get_membership(self.labels_, n_labels=n_labels)
158
+ probs_col = normalize(input_matrix.T.dot(probs_row))
159
+ else:
160
+ n_labels = max(max(self.labels_row_), max(self.labels_col_)) + 1
161
+ probs_row = get_membership(self.labels_row_, n_labels=n_labels)
162
+ probs_col = get_membership(self.labels_col_, n_labels=n_labels)
163
+ if self.return_probs:
164
+ self.probs_row_ = normalize(input_matrix.dot(probs_col))
165
+ self.probs_col_ = normalize(input_matrix.T.dot(probs_row))
166
+ self.probs_ = self.probs_row_
167
+ if self.return_aggregate:
168
+ aggregate_ = sparse.csr_matrix(probs_row.T.dot(input_matrix))
169
+ aggregate_ = aggregate_.dot(probs_col)
170
+ self.aggregate_ = aggregate_
171
+
172
+ return self
@@ -0,0 +1,253 @@
1
+ """
2
+ Created in March 2024
3
+ @author: Laurène David <laurene.david@ip-paris.fr>
4
+ @author: Thomas Bonald <bonald@enst.fr>
5
+ """
6
+
7
+ from typing import Union
8
+
9
+ import numpy as np
10
+ from scipy import sparse
11
+
12
+ from sknetwork.clustering import BaseClustering
13
+ from sknetwork.ranking import PageRank
14
+ from sknetwork.clustering import get_modularity
15
+ from sknetwork.classification.pagerank import PageRankClassifier
16
+ from sknetwork.utils.format import get_adjacency, directed2undirected
17
+
18
+
19
+ class KCenters(BaseClustering):
20
+ """K-center clustering algorithm. The center of each cluster is obtained by the PageRank algorithm.
21
+
22
+ Parameters
23
+ ----------
24
+ n_clusters : int
25
+ Number of clusters.
26
+ directed : bool, default False
27
+ If ``True``, the graph is considered directed.
28
+ center_position : str, default "row"
29
+ Force centers to correspond to the nodes on the rows or columns of the biadjacency matrix.
30
+ Can be ``row``, ``col`` or ``both``. Only considered for bipartite graphs.
31
+ n_init : int, default 5
32
+ Number of reruns of the k-centers algorithm with different centers.
33
+ The run that produce the best modularity is chosen as the final result.
34
+ max_iter : int, default 20
35
+ Maximum number of iterations of the k-centers algorithm for a single run.
36
+
37
+ Attributes
38
+ ----------
39
+ labels_ : np.ndarray, shape (n_nodes,)
40
+ Label of each node.
41
+ labels_row_, labels_col_ : np.ndarray
42
+ Labels of rows and columns, for bipartite graphs.
43
+ centers_ : np.ndarray, shape (n_nodes,)
44
+ Cluster centers.
45
+ centers_row_, centers_col_ : np.ndarray
46
+ Cluster centers of rows and columns, for bipartite graphs.
47
+
48
+ Example
49
+ -------
50
+ >>> from sknetwork.clustering import KCenters
51
+ >>> from sknetwork.data import karate_club
52
+ >>> kcenters = KCenters(n_clusters=2)
53
+ >>> adjacency = karate_club()
54
+ >>> labels = kcenters.fit_predict(adjacency)
55
+ >>> len(set(labels))
56
+ 2
57
+
58
+ """
59
+ def __init__(self, n_clusters: int, directed: bool = False, center_position: str = "row", n_init: int = 5,
60
+ max_iter: int = 20):
61
+ super(BaseClustering, self).__init__()
62
+ self.n_clusters = n_clusters
63
+ self.directed = directed
64
+ self.bipartite = None
65
+ self.center_position = center_position
66
+ self.n_init = n_init
67
+ self.max_iter = max_iter
68
+ self.labels_ = None
69
+ self.centers_ = None
70
+ self.centers_row_ = None
71
+ self.centers_col_ = None
72
+
73
+ def _compute_mask_centers(self, input_matrix: Union[sparse.csr_matrix, np.ndarray]):
74
+ """Generate mask to filter nodes that can be cluster centers.
75
+
76
+ Parameters
77
+ ----------
78
+ input_matrix :
79
+ Adjacency matrix or biadjacency matrix of the graph.
80
+
81
+ Return
82
+ ------
83
+ mask : np.array, shape (n_nodes,)
84
+ Mask for possible cluster centers.
85
+
86
+ """
87
+ n_row, n_col = input_matrix.shape
88
+ if self.bipartite:
89
+ n_nodes = n_row + n_col
90
+ mask = np.zeros(n_nodes, dtype=bool)
91
+ if self.center_position == "row":
92
+ mask[:n_row] = True
93
+ elif self.center_position == "col":
94
+ mask[n_row:] = True
95
+ elif self.center_position == "both":
96
+ mask[:] = True
97
+ else:
98
+ raise ValueError('Unknown center position')
99
+ else:
100
+ mask = np.ones(n_row, dtype=bool)
101
+
102
+ return mask
103
+
104
+ @staticmethod
105
+ def _init_centers(adjacency: Union[sparse.csr_matrix, np.ndarray], mask: np.ndarray, n_clusters: int):
106
+ """
107
+ Kcenters++ initialization to select cluster centers.
108
+ This algorithm is an adaptation of the Kmeans++ algorithm to graphs.
109
+
110
+ Parameters
111
+ ----------
112
+ adjacency :
113
+ Adjacency matrix of the graph.
114
+ mask :
115
+ Initial mask for allowed positions of centers.
116
+ n_clusters : int
117
+ Number of centers to initialize.
118
+
119
+ Returns
120
+ ---------
121
+ centers : np.array, shape (n_clusters,)
122
+ Initial cluster centers.
123
+ """
124
+ mask = mask.copy()
125
+ n_nodes = adjacency.shape[0]
126
+ nodes = np.arange(n_nodes)
127
+ centers = []
128
+
129
+ # Choose the first center uniformly at random
130
+ center = np.random.choice(nodes[mask])
131
+ mask[center] = 0
132
+ centers.append(center)
133
+
134
+ pagerank = PageRank()
135
+ weights = {center: 1}
136
+
137
+ for k in range(n_clusters - 1):
138
+ # select nodes that are far from existing centers
139
+ ppr_scores = pagerank.fit_predict(adjacency, weights)
140
+ ppr_scores = ppr_scores[mask]
141
+
142
+ if min(ppr_scores) == 0:
143
+ center = np.random.choice(nodes[mask][ppr_scores == 0])
144
+ else:
145
+ probs = 1 / ppr_scores
146
+ probs = probs / np.sum(probs)
147
+ center = np.random.choice(nodes[mask], p=probs)
148
+
149
+ mask[center] = 0
150
+ centers.append(center)
151
+ weights.update({center: 1})
152
+
153
+ centers = np.array(centers)
154
+ return centers
155
+
156
+ def fit(self, input_matrix: Union[sparse.csr_matrix, np.ndarray], force_bipartite: bool = False) -> "KCenters":
157
+ """Compute the clustering of the graph by k-centers.
158
+
159
+ Parameters
160
+ ----------
161
+ input_matrix :
162
+ Adjacency matrix or biadjacency matrix of the graph.
163
+ force_bipartite :
164
+ If ``True``, force the input matrix to be considered as a biadjacency matrix even if square.
165
+
166
+ Returns
167
+ -------
168
+ self : :class:`KCenters`
169
+ """
170
+
171
+ if self.n_clusters < 2:
172
+ raise ValueError("The number of clusters must be at least 2.")
173
+
174
+ if self.n_init < 1:
175
+ raise ValueError("The n_init parameter must be at least 1.")
176
+
177
+ if self.directed:
178
+ input_matrix = directed2undirected(input_matrix)
179
+
180
+ adjacency, self.bipartite = get_adjacency(input_matrix, force_bipartite=force_bipartite)
181
+ n_row = input_matrix.shape[0]
182
+ n_nodes = adjacency.shape[0]
183
+ nodes = np.arange(n_nodes)
184
+
185
+ mask = self._compute_mask_centers(input_matrix)
186
+ if self.n_clusters > np.sum(mask):
187
+ raise ValueError("The number of clusters is to high. This might be due to the center_position parameter.")
188
+
189
+ pagerank_clf = PageRankClassifier()
190
+ pagerank = PageRank()
191
+
192
+ labels_ = []
193
+ centers_ = []
194
+ modularity_ = []
195
+
196
+ # Restarts
197
+ for i in range(self.n_init):
198
+
199
+ # Initialization
200
+ centers = self._init_centers(adjacency, mask, self.n_clusters)
201
+ prev_centers = None
202
+ labels = None
203
+ n_iter = 0
204
+
205
+ while not np.equal(prev_centers, centers).all() and (n_iter < self.max_iter):
206
+
207
+ # Assign nodes to centers
208
+ labels_center = {center: label for label, center in enumerate(centers)}
209
+ labels = pagerank_clf.fit_predict(adjacency, labels_center)
210
+
211
+ # Find new centers
212
+ prev_centers = centers.copy()
213
+ new_centers = []
214
+
215
+ for label in np.unique(labels):
216
+ mask_cluster = labels == label
217
+ mask_cluster &= mask
218
+ scores = pagerank.fit_predict(adjacency, weights=mask_cluster)
219
+ scores[~mask_cluster] = 0
220
+ new_centers.append(nodes[np.argmax(scores)])
221
+
222
+ n_iter += 1
223
+
224
+ # Store results
225
+ if self.bipartite:
226
+ labels_row = labels[:n_row]
227
+ labels_col = labels[n_row:]
228
+ modularity = get_modularity(input_matrix, labels_row, labels_col)
229
+ else:
230
+ modularity = get_modularity(adjacency, labels)
231
+
232
+ labels_.append(labels)
233
+ centers_.append(centers)
234
+ modularity_.append(modularity)
235
+
236
+ # Select restart with the highest modularity
237
+ idx_max = np.argmax(modularity_)
238
+ self.labels_ = np.array(labels_[idx_max])
239
+ self.centers_ = np.array(centers_[idx_max])
240
+
241
+ if self.bipartite:
242
+ self._split_vars(input_matrix.shape)
243
+
244
+ # Define centers based on center position
245
+ if self.center_position == "row":
246
+ self.centers_row_ = self.centers_
247
+ elif self.center_position == "col":
248
+ self.centers_col_ = self.centers_ - n_row
249
+ else:
250
+ self.centers_row_ = self.centers_[self.centers_ < n_row]
251
+ self.centers_col_ = self.centers_[~np.isin(self.centers_, self.centers_row_)] - n_row
252
+
253
+ return self