graphslim 1.0.1__py3-none-any.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.
Files changed (146) hide show
  1. graphslim/__init__.py +0 -0
  2. graphslim/coarsening/__init__.py +12 -0
  3. graphslim/coarsening/affinity_gs.py +110 -0
  4. graphslim/coarsening/algebraic_jc.py +110 -0
  5. graphslim/coarsening/averaging.py +58 -0
  6. graphslim/coarsening/clustering.py +64 -0
  7. graphslim/coarsening/clusteringagg.py +77 -0
  8. graphslim/coarsening/coarsening_base.py +246 -0
  9. graphslim/coarsening/heavy_edge.py +110 -0
  10. graphslim/coarsening/kron.py +109 -0
  11. graphslim/coarsening/utils.py +2002 -0
  12. graphslim/coarsening/variation_cliques.py +131 -0
  13. graphslim/coarsening/variation_edges.py +131 -0
  14. graphslim/coarsening/variation_neighborhoods.py +131 -0
  15. graphslim/coarsening/vng.py +118 -0
  16. graphslim/condensation/__init__.py +9 -0
  17. graphslim/condensation/doscond.py +64 -0
  18. graphslim/condensation/doscondx.py +59 -0
  19. graphslim/condensation/gcond.py +80 -0
  20. graphslim/condensation/gcond_base.py +186 -0
  21. graphslim/condensation/gcondx.py +76 -0
  22. graphslim/condensation/gcsntk.py +160 -0
  23. graphslim/condensation/geom.py +449 -0
  24. graphslim/condensation/msgc.py +244 -0
  25. graphslim/condensation/sfgc.py +215 -0
  26. graphslim/condensation/sgdd.py +102 -0
  27. graphslim/condensation/utils.py +236 -0
  28. graphslim/configs/doscond/citeseer.json +8 -0
  29. graphslim/configs/doscond/cora.json +8 -0
  30. graphslim/configs/doscond/flickr.json +8 -0
  31. graphslim/configs/doscond/ogbn-arxiv.json +9 -0
  32. graphslim/configs/doscond/reddit.json +9 -0
  33. graphslim/configs/doscondx/citeseer.json +8 -0
  34. graphslim/configs/doscondx/cora.json +8 -0
  35. graphslim/configs/doscondx/flickr.json +7 -0
  36. graphslim/configs/doscondx/ogbn-arxiv.json +8 -0
  37. graphslim/configs/doscondx/reddit.json +7 -0
  38. graphslim/configs/gcond/citeseer.json +11 -0
  39. graphslim/configs/gcond/cora.json +11 -0
  40. graphslim/configs/gcond/flickr.json +10 -0
  41. graphslim/configs/gcond/ogbn-arxiv.json +11 -0
  42. graphslim/configs/gcond/reddit.json +11 -0
  43. graphslim/configs/gcondx/citeseer.json +8 -0
  44. graphslim/configs/gcondx/cora.json +8 -0
  45. graphslim/configs/gcondx/flickr.json +7 -0
  46. graphslim/configs/gcondx/ogbn-arxiv.json +8 -0
  47. graphslim/configs/gcondx/reddit.json +11 -0
  48. graphslim/configs/gcsntk/citeseer.json +11 -0
  49. graphslim/configs/gcsntk/cora.json +11 -0
  50. graphslim/configs/gcsntk/flickr.json +13 -0
  51. graphslim/configs/gcsntk/ogbn-arxiv.json +13 -0
  52. graphslim/configs/gcsntk/reddit.json +13 -0
  53. graphslim/configs/geom/citeseer.json +26 -0
  54. graphslim/configs/geom/cora.json +25 -0
  55. graphslim/configs/geom/flickr.json +30 -0
  56. graphslim/configs/geom/ogbn-arxiv.json +27 -0
  57. graphslim/configs/geom/reddit.json +29 -0
  58. graphslim/configs/msgc/citeseer.json +12 -0
  59. graphslim/configs/msgc/cora.json +12 -0
  60. graphslim/configs/msgc/flickr.json +12 -0
  61. graphslim/configs/msgc/ogbn-arxiv.json +12 -0
  62. graphslim/configs/msgc/reddit.json +12 -0
  63. graphslim/configs/sfgc/citeseer.json +12 -0
  64. graphslim/configs/sfgc/cora.json +12 -0
  65. graphslim/configs/sfgc/flickr.json +12 -0
  66. graphslim/configs/sfgc/ogbn-arxiv.json +12 -0
  67. graphslim/configs/sfgc/reddit.json +12 -0
  68. graphslim/configs/sgdd/citeseer.json +16 -0
  69. graphslim/configs/sgdd/cora.json +16 -0
  70. graphslim/configs/sgdd/flickr.json +15 -0
  71. graphslim/configs/sgdd/ogbn-arxiv.json +17 -0
  72. graphslim/configs/sgdd/reddit.json +17 -0
  73. graphslim/configs.py +193 -0
  74. graphslim/dataset/__init__.py +3 -0
  75. graphslim/dataset/attack.py +95 -0
  76. graphslim/dataset/convertor.py +257 -0
  77. graphslim/dataset/loader.py +404 -0
  78. graphslim/dataset/utils.py +374 -0
  79. graphslim/evaluation/__init__.py +3 -0
  80. graphslim/evaluation/eval_agent.py +210 -0
  81. graphslim/evaluation/nas_eval.py +161 -0
  82. graphslim/evaluation/utils.py +145 -0
  83. graphslim/evaluation/vis.py +73 -0
  84. graphslim/models/__init__.py +13 -0
  85. graphslim/models/appnp.py +196 -0
  86. graphslim/models/base.py +212 -0
  87. graphslim/models/cheby.py +29 -0
  88. graphslim/models/gat.py +80 -0
  89. graphslim/models/gcn.py +23 -0
  90. graphslim/models/gntk.py +166 -0
  91. graphslim/models/graphsage.py +149 -0
  92. graphslim/models/ignr.py +213 -0
  93. graphslim/models/krr.py +21 -0
  94. graphslim/models/layers.py +379 -0
  95. graphslim/models/parametrized_adj.py +86 -0
  96. graphslim/models/prbcd.py +445 -0
  97. graphslim/models/random_attack.py +162 -0
  98. graphslim/models/reparam_module.py +150 -0
  99. graphslim/models/sgc.py +86 -0
  100. graphslim/models/sgformer.py +476 -0
  101. graphslim/models/sntk.py +96 -0
  102. graphslim/sparsification/__init__.py +15 -0
  103. graphslim/sparsification/cent_degree.py +28 -0
  104. graphslim/sparsification/cent_pagerank.py +55 -0
  105. graphslim/sparsification/coreset_base.py +46 -0
  106. graphslim/sparsification/edge_sparsification_base.py +34 -0
  107. graphslim/sparsification/fixed_idx/idx_citeseer_0.1_kcenter_15.npy +0 -0
  108. graphslim/sparsification/fixed_idx/idx_citeseer_0.25_kcenter_15.npy +0 -0
  109. graphslim/sparsification/fixed_idx/idx_citeseer_0.5_kcenter_15.npy +0 -0
  110. graphslim/sparsification/fixed_idx/idx_citeseer_1.0_kcenter_15.npy +0 -0
  111. graphslim/sparsification/fixed_idx/idx_cora_0.1_kcenter_15.npy +0 -0
  112. graphslim/sparsification/fixed_idx/idx_cora_0.25_kcenter_15.npy +0 -0
  113. graphslim/sparsification/fixed_idx/idx_cora_0.5_kcenter_15.npy +0 -0
  114. graphslim/sparsification/fixed_idx/idx_cora_1.0_kcenter_15.npy +0 -0
  115. graphslim/sparsification/fixed_idx/idx_flickr_0.001_kcenter_15.npy +0 -0
  116. graphslim/sparsification/fixed_idx/idx_flickr_0.005_kcenter_15.npy +0 -0
  117. graphslim/sparsification/fixed_idx/idx_flickr_0.01_kcenter_15.npy +0 -0
  118. graphslim/sparsification/fixed_idx/idx_ogbn-arxiv_0.001_kcenter_15.npy +0 -0
  119. graphslim/sparsification/fixed_idx/idx_ogbn-arxiv_0.005_kcenter_15.npy +0 -0
  120. graphslim/sparsification/fixed_idx/idx_ogbn-arxiv_0.01_kcenter_15.npy +0 -0
  121. graphslim/sparsification/fixed_idx/idx_reddit_0.0005_kcenter_15.npy +0 -0
  122. graphslim/sparsification/fixed_idx/idx_reddit_0.001_kcenter_15.npy +0 -0
  123. graphslim/sparsification/fixed_idx/idx_reddit_0.002_kcenter_15.npy +0 -0
  124. graphslim/sparsification/fixed_idx/idx_reddit_0.005_kcenter_15.npy +0 -0
  125. graphslim/sparsification/g_spar.py +21 -0
  126. graphslim/sparsification/herding.py +25 -0
  127. graphslim/sparsification/herding_agg.py +25 -0
  128. graphslim/sparsification/kcenter.py +24 -0
  129. graphslim/sparsification/kcenter_agg.py +27 -0
  130. graphslim/sparsification/kcenter_sample.py +79 -0
  131. graphslim/sparsification/local_degree.py +21 -0
  132. graphslim/sparsification/model_based_coreset_base.py +63 -0
  133. graphslim/sparsification/model_free_coreset_base.py +61 -0
  134. graphslim/sparsification/random.py +17 -0
  135. graphslim/sparsification/random_edge.py +21 -0
  136. graphslim/sparsification/rank_degree.py +68 -0
  137. graphslim/sparsification/scan.py +21 -0
  138. graphslim/sparsification/spanning_forest.py +19 -0
  139. graphslim/sparsification/t_spanner.py +28 -0
  140. graphslim/sparsification/utils.py +0 -0
  141. graphslim/train_all.py +69 -0
  142. graphslim/utils.py +946 -0
  143. graphslim-1.0.1.dist-info/METADATA +34 -0
  144. graphslim-1.0.1.dist-info/RECORD +146 -0
  145. graphslim-1.0.1.dist-info/WHEEL +5 -0
  146. graphslim-1.0.1.dist-info/top_level.txt +1 -0
graphslim/__init__.py ADDED
File without changes
@@ -0,0 +1,12 @@
1
+ from .coarsening_base import Coarsen
2
+ from .vng import VNG
3
+ from .clustering import Cluster
4
+ from .clusteringagg import ClusterAgg
5
+ from .averaging import Average
6
+ from .variation_neighborhoods import VariationNeighborhoods
7
+ from .variation_edges import VariationEdges
8
+ from .variation_cliques import VariationCliques
9
+ from .heavy_edge import HeavyEdge
10
+ from .algebraic_jc import AlgebraicJc
11
+ from .affinity_gs import AffinityGs
12
+ from .kron import Kron
@@ -0,0 +1,110 @@
1
+ import copy
2
+
3
+ import numpy as np
4
+ import scipy as sp
5
+ import torch
6
+ from pygsp import graphs
7
+ from torch_geometric.utils import to_dense_adj
8
+
9
+ from graphslim.coarsening.utils import contract_variation_edges, contract_variation_linear, get_proximity_measure, \
10
+ matching_optimal, matching_greedy, get_coarsening_matrix, coarsen_matrix, coarsen_vector, zero_diag
11
+ from graphslim.dataset.convertor import pyg2gsp, csr2ei, ei2csr
12
+ from graphslim.dataset.utils import save_reduced
13
+ from graphslim.evaluation import *
14
+ from graphslim.utils import one_hot, to_tensor
15
+ from graphslim.coarsening.coarsening_base import Coarsen
16
+
17
+
18
+ class AffinityGs(Coarsen):
19
+
20
+ def coarsen(self, G):
21
+ """
22
+ This function provides a common interface for coarsening algorithms that contract subgraphs
23
+
24
+ Parameters
25
+ ----------
26
+ G : pygsp Graph
27
+ K : int
28
+ The size of the subspace we are interested in preserving.
29
+ r : float between (0,1)
30
+ The desired reduction defined as 1 - n/N.
31
+ method : String
32
+ ['variation_neighborhoods', 'variation_edges', 'variation_cliques', 'heavy_edge', 'algebraic_JC', 'affinity_GS', 'kron']
33
+
34
+ Returns
35
+ -------
36
+ C : np.array of size n x N
37
+ The coarsening matrix.
38
+ Gc : pygsp Graph
39
+ The smaller graph.
40
+ Call : list of np.arrays
41
+ Coarsening matrices for each level
42
+ Gall : list of (n_levels+1) pygsp Graphs
43
+ All graphs involved in the multilevel coarsening
44
+
45
+ Example
46
+ -------
47
+ C, Gc, Call, Gall = coarsen(G, K=10, r=0.8)
48
+ """
49
+ K = 10
50
+ r = 0.5
51
+ max_levels = 10
52
+ Uk = None
53
+ lk = None
54
+ max_level_r = 0.99,
55
+ r = np.clip(r, 0, 0.999)
56
+ G0 = G
57
+ N = G.N
58
+
59
+ # current and target graph sizes
60
+ n, n_target = N, np.ceil((1 - r) * N)
61
+
62
+ C = sp.sparse.eye(N, format="csc")
63
+ Gc = G
64
+
65
+ Call, Gall = [], []
66
+ Gall.append(G)
67
+ method = "affinity_GS"
68
+ algorithm=self.args.coarsen_strategy
69
+ # algorithm = "greedy"
70
+ for level in range(1, max_levels + 1):
71
+
72
+ G = Gc
73
+
74
+ # how much more we need to reduce the current graph
75
+ r_cur = np.clip(1 - n_target / n, 0.0, max_level_r)
76
+
77
+ weights = get_proximity_measure(G, method, K=K)
78
+
79
+ if algorithm == "optimal":
80
+ # the edge-weight should be light at proximal edges
81
+ weights = -weights
82
+ if "rss" not in method:
83
+ weights -= min(weights)
84
+ coarsening_list = matching_optimal(G, weights=weights, r=r_cur)
85
+
86
+ elif algorithm == "greedy":
87
+ coarsening_list = matching_greedy(G, weights=weights, r=r_cur)
88
+ iC = get_coarsening_matrix(G, coarsening_list)
89
+
90
+ if iC.shape[1] - iC.shape[0] <= 2:
91
+ break # avoid too many levels for so few nodes
92
+
93
+ C = iC.dot(C)
94
+ Call.append(iC)
95
+
96
+ Wc = zero_diag(coarsen_matrix(G.W, iC)) # coarsen and remove self-loops
97
+ Wc = (Wc + Wc.T) / 2 # this is only needed to avoid pygsp complaining for tiny errors
98
+
99
+ if not hasattr(G, "coords"):
100
+ Gc = graphs.Graph(Wc)
101
+ else:
102
+ Gc = graphs.Graph(Wc, coords=coarsen_vector(G.coords, iC))
103
+ Gall.append(Gc)
104
+
105
+ n = Gc.N
106
+
107
+ if n <= n_target:
108
+ break
109
+
110
+ return C, Gc, Call, Gall
@@ -0,0 +1,110 @@
1
+ import copy
2
+
3
+ import numpy as np
4
+ import scipy as sp
5
+ import torch
6
+ from pygsp import graphs
7
+ from torch_geometric.utils import to_dense_adj
8
+
9
+ from graphslim.coarsening.utils import contract_variation_edges, contract_variation_linear, get_proximity_measure, \
10
+ matching_optimal, matching_greedy, get_coarsening_matrix, coarsen_matrix, coarsen_vector, zero_diag
11
+ from graphslim.dataset.convertor import pyg2gsp, csr2ei, ei2csr
12
+ from graphslim.dataset.utils import save_reduced
13
+ from graphslim.evaluation import *
14
+ from graphslim.utils import one_hot, to_tensor
15
+ from graphslim.coarsening.coarsening_base import Coarsen
16
+
17
+
18
+ class AlgebraicJc(Coarsen):
19
+
20
+ def coarsen(self, G):
21
+ """
22
+ This function provides a common interface for coarsening algorithms that contract subgraphs
23
+
24
+ Parameters
25
+ ----------
26
+ G : pygsp Graph
27
+ K : int
28
+ The size of the subspace we are interested in preserving.
29
+ r : float between (0,1)
30
+ The desired reduction defined as 1 - n/N.
31
+ method : String
32
+ ['variation_neighborhoods', 'variation_edges', 'variation_cliques', 'heavy_edge', 'algebraic_JC', 'affinity_GS', 'kron']
33
+
34
+ Returns
35
+ -------
36
+ C : np.array of size n x N
37
+ The coarsening matrix.
38
+ Gc : pygsp Graph
39
+ The smaller graph.
40
+ Call : list of np.arrays
41
+ Coarsening matrices for each level
42
+ Gall : list of (n_levels+1) pygsp Graphs
43
+ All graphs involved in the multilevel coarsening
44
+
45
+ Example
46
+ -------
47
+ C, Gc, Call, Gall = coarsen(G, K=10, r=0.8)
48
+ """
49
+ K = 10
50
+ r = 0.5
51
+ max_levels = 10
52
+ Uk = None
53
+ lk = None
54
+ max_level_r = 0.99,
55
+ r = np.clip(r, 0, 0.999)
56
+ G0 = G
57
+ N = G.N
58
+
59
+ # current and target graph sizes
60
+ n, n_target = N, np.ceil((1 - r) * N)
61
+
62
+ C = sp.sparse.eye(N, format="csc")
63
+ Gc = G
64
+
65
+ Call, Gall = [], []
66
+ Gall.append(G)
67
+ method = "algebraic_JC"
68
+ algorithm=self.args.coarsen_strategy
69
+ # algorithm = "greedy"
70
+ for level in range(1, max_levels + 1):
71
+
72
+ G = Gc
73
+
74
+ # how much more we need to reduce the current graph
75
+ r_cur = np.clip(1 - n_target / n, 0.0, max_level_r)
76
+
77
+ weights = get_proximity_measure(G, method, K=K)
78
+
79
+ if algorithm == "optimal":
80
+ # the edge-weight should be light at proximal edges
81
+ weights = -weights
82
+ if "rss" not in method:
83
+ weights -= min(weights)
84
+ coarsening_list = matching_optimal(G, weights=weights, r=r_cur)
85
+
86
+ elif algorithm == "greedy":
87
+ coarsening_list = matching_greedy(G, weights=weights, r=r_cur)
88
+ iC = get_coarsening_matrix(G, coarsening_list)
89
+
90
+ if iC.shape[1] - iC.shape[0] <= 2:
91
+ break # avoid too many levels for so few nodes
92
+
93
+ C = iC.dot(C)
94
+ Call.append(iC)
95
+
96
+ Wc = zero_diag(coarsen_matrix(G.W, iC)) # coarsen and remove self-loops
97
+ Wc = (Wc + Wc.T) / 2 # this is only needed to avoid pygsp complaining for tiny errors
98
+
99
+ if not hasattr(G, "coords"):
100
+ Gc = graphs.Graph(Wc)
101
+ else:
102
+ Gc = graphs.Graph(Wc, coords=coarsen_vector(G.coords, iC))
103
+ Gall.append(Gc)
104
+
105
+ n = Gc.N
106
+
107
+ if n <= n_target:
108
+ break
109
+
110
+ return C, Gc, Call, Gall
@@ -0,0 +1,58 @@
1
+ from collections import Counter
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from graphslim.coarsening.coarsening_base import Coarsen
7
+ from graphslim.dataset.utils import save_reduced
8
+ from graphslim.evaluation.utils import verbose_time_memory
9
+
10
+
11
+ class Average(Coarsen):
12
+ # a structure free coarsening method
13
+ # also serve as initialization for condensation methods
14
+ # output: feat_syn, label_syn
15
+ def __init__(self, setting, data, args, **kwargs):
16
+ super(Average, self).__init__(setting, data, args, **kwargs)
17
+
18
+ @verbose_time_memory
19
+ def reduce(self, data, verbose=True, save=True):
20
+ args = self.args
21
+ n_classes = data.nclass
22
+ if hasattr(data, 'labels_syn'):
23
+ y_syn = data.labels_syn
24
+ self.labels_train = data.labels_train
25
+ y_train = data.labels_train
26
+ x_train = data.feat_train
27
+ else:
28
+ y_syn, y_train, x_train = self.prepare_select(data, args)
29
+ x_syn = torch.zeros(y_syn.shape[0], x_train.shape[1])
30
+ for c in range(n_classes):
31
+ x_c = x_train[y_train == c]
32
+ x_syn[y_syn == c] = x_c.mean(0)
33
+ data.feat_syn, data.labels_syn = x_syn.to(x_train.device), y_syn
34
+ data.adj_syn = torch.eye(data.feat_syn.shape[0])
35
+ if save:
36
+ save_reduced(data.adj_syn, data.feat_syn, data.labels_syn, args)
37
+ return data
38
+
39
+ def prepare_select(self, data, args):
40
+ num_class_dict = {}
41
+ syn_class_indices = {}
42
+ feat_train = data.feat_train
43
+
44
+ labels_train = data.labels_train
45
+ # d = data.feat_train.shape[1]
46
+ counter = Counter(data.labels_train.tolist())
47
+ # n = len(data.labels_train)
48
+ sorted_counter = sorted(counter.items(), key=lambda x: x[1])
49
+ sum_ = 0
50
+ labels_syn = []
51
+ for ix, (c, num) in enumerate(sorted_counter):
52
+ num_class_dict[c] = max(int(num * args.reduction_rate), 1)
53
+ sum_ += num_class_dict[c]
54
+ syn_class_indices[c] = [len(labels_syn), len(labels_syn) + num_class_dict[c]]
55
+ labels_syn += [c] * num_class_dict[c]
56
+ labels_syn = np.array(labels_syn)
57
+
58
+ return labels_syn, labels_train, feat_train
@@ -0,0 +1,64 @@
1
+ from collections import Counter
2
+
3
+ import numpy as np
4
+ import torch
5
+ from sklearn.cluster import BisectingKMeans
6
+ from torch_scatter import scatter_mean
7
+
8
+ from graphslim.coarsening.coarsening_base import Coarsen
9
+ from graphslim.dataset.utils import save_reduced
10
+ from graphslim.evaluation.utils import verbose_time_memory
11
+
12
+
13
+ class Cluster(Coarsen):
14
+ # a structure free coarsening method
15
+ # also serve as initialization for condensation methods
16
+ # output: feat_syn, label_syn
17
+ def __init__(self, setting, data, args, **kwargs):
18
+ super(Cluster, self).__init__(setting, data, args, **kwargs)
19
+
20
+ @verbose_time_memory
21
+ def reduce(self, data, verbose=True, save=True):
22
+ args = self.args
23
+ n_classes = data.nclass
24
+ if hasattr(data, 'labels_syn') and data.labels_syn is not None:
25
+ y_syn = data.labels_syn
26
+ self.labels_train = data.labels_train
27
+ y_train = data.labels_train
28
+ x_train = data.feat_train
29
+ else:
30
+ y_syn, y_train, x_train = self.prepare_select(data, args)
31
+ x_syn = torch.zeros(y_syn.shape[0], x_train.shape[1])
32
+ for c in range(n_classes):
33
+ x_c = x_train[y_train == c].cpu()
34
+ n_c = (y_syn == c).sum().item()
35
+ k_means = BisectingKMeans(n_clusters=n_c, random_state=0)
36
+ k_means.fit(x_c)
37
+ clusters = torch.from_numpy(k_means.predict(x_c)).long()
38
+ x_syn[y_syn == c] = scatter_mean(x_c, clusters, dim=0)
39
+ data.feat_syn, data.labels_syn = x_syn.to(x_train.device), y_syn
40
+ data.adj_syn = torch.eye(data.feat_syn.shape[0])
41
+ if save:
42
+ save_reduced(data.adj_syn, data.feat_syn, data.labels_syn, args)
43
+ return data
44
+
45
+ def prepare_select(self, data, args):
46
+ num_class_dict = {}
47
+ syn_class_indices = {}
48
+ feat_train = data.feat_train
49
+
50
+ labels_train = data.labels_train
51
+ # d = data.feat_train.shape[1]
52
+ counter = Counter(data.labels_train.tolist())
53
+ # n = len(data.labels_train)
54
+ sorted_counter = sorted(counter.items(), key=lambda x: x[1])
55
+ sum_ = 0
56
+ labels_syn = []
57
+ for ix, (c, num) in enumerate(sorted_counter):
58
+ num_class_dict[c] = max(int(num * args.reduction_rate), 1)
59
+ sum_ += num_class_dict[c]
60
+ syn_class_indices[c] = [len(labels_syn), len(labels_syn) + num_class_dict[c]]
61
+ labels_syn += [c] * num_class_dict[c]
62
+ labels_syn = np.array(labels_syn)
63
+
64
+ return labels_syn, labels_train, feat_train
@@ -0,0 +1,77 @@
1
+ from collections import Counter
2
+
3
+ import numpy as np
4
+ import torch
5
+ from sklearn.cluster import BisectingKMeans
6
+ from torch_scatter import scatter_mean
7
+
8
+ from graphslim.coarsening.coarsening_base import Coarsen
9
+ from graphslim.dataset.utils import save_reduced
10
+ from graphslim.evaluation.utils import verbose_time_memory
11
+
12
+ from torch_sparse import matmul
13
+ from graphslim.utils import normalize_adj_tensor, to_tensor
14
+
15
+
16
+ class ClusterAgg(Coarsen):
17
+ # a structure free coarsening method
18
+ # also serve as initialization for condensation methods
19
+ # output: feat_syn, label_syn
20
+ def __init__(self, setting, data, args, **kwargs):
21
+ super(ClusterAgg, self).__init__(setting, data, args, **kwargs)
22
+
23
+ @verbose_time_memory
24
+ def reduce(self, data, verbose=True, save=True):
25
+ args = self.args
26
+ n_classes = data.nclass
27
+ if args.setting == 'trans':
28
+ data.adj_fully = to_tensor(data.adj_full)
29
+ data.pre_conv = normalize_adj_tensor(data.adj_fully, sparse=True)
30
+ data.pre_conv = matmul(data.pre_conv, data.pre_conv)
31
+ feat_agg = matmul(data.pre_conv, data.feat_full).float()
32
+ else:
33
+ data.adj_fully = to_tensor(data.adj_train)
34
+ data.pre_conv = normalize_adj_tensor(data.adj_fully, sparse=True)
35
+ data.pre_conv = matmul(data.pre_conv, data.pre_conv)
36
+ feat_agg = matmul(data.pre_conv, data.feat_train).float()
37
+
38
+ if hasattr(data, 'labels_syn') and data.labels_syn is not None:
39
+ y_syn = data.labels_syn
40
+ self.labels_train = data.labels_train
41
+ y_train = data.labels_train
42
+ else:
43
+ y_syn, y_train = self.prepare_select(data, args)
44
+ x_train = feat_agg[data.train_mask] if args.setting == 'trans' else feat_agg
45
+ x_syn = torch.zeros(y_syn.shape[0], x_train.shape[1])
46
+ for c in range(n_classes):
47
+ x_c = x_train[y_train == c].cpu()
48
+ n_c = (y_syn == c).sum().item()
49
+ k_means = BisectingKMeans(n_clusters=n_c, random_state=0)
50
+ k_means.fit(x_c)
51
+ clusters = torch.from_numpy(k_means.predict(x_c)).long()
52
+ x_syn[y_syn == c] = scatter_mean(x_c, clusters, dim=0)
53
+ data.feat_syn, data.labels_syn = x_syn.to(x_train.device), y_syn
54
+ data.adj_syn = torch.eye(data.feat_syn.shape[0])
55
+ if save:
56
+ save_reduced(data.adj_syn, data.feat_syn, data.labels_syn, args)
57
+ return data
58
+
59
+ def prepare_select(self, data, args):
60
+ num_class_dict = {}
61
+ syn_class_indices = {}
62
+
63
+ labels_train = data.labels_train
64
+ # d = data.feat_train.shape[1]
65
+ counter = Counter(data.labels_train.tolist())
66
+ # n = len(data.labels_train)
67
+ sorted_counter = sorted(counter.items(), key=lambda x: x[1])
68
+ sum_ = 0
69
+ labels_syn = []
70
+ for ix, (c, num) in enumerate(sorted_counter):
71
+ num_class_dict[c] = max(int(num * args.reduction_rate), 1)
72
+ sum_ += num_class_dict[c]
73
+ syn_class_indices[c] = [len(labels_syn), len(labels_syn) + num_class_dict[c]]
74
+ labels_syn += [c] * num_class_dict[c]
75
+ labels_syn = np.array(labels_syn)
76
+
77
+ return labels_syn, labels_train
@@ -0,0 +1,246 @@
1
+ import copy
2
+
3
+ import numpy as np
4
+ import scipy as sp
5
+ import torch
6
+ from pygsp import graphs
7
+ from torch_geometric.utils import to_dense_adj
8
+
9
+ from graphslim.coarsening.utils import contract_variation_edges, contract_variation_linear, get_proximity_measure, \
10
+ matching_optimal, matching_greedy, get_coarsening_matrix, coarsen_matrix, coarsen_vector, zero_diag
11
+ from graphslim.dataset.convertor import pyg2gsp, csr2ei, ei2csr
12
+ from graphslim.dataset.utils import save_reduced
13
+ from graphslim.evaluation import *
14
+ from graphslim.utils import one_hot, to_tensor
15
+
16
+
17
+ class Coarsen:
18
+ def __init__(self, setting, data, args, **kwargs):
19
+ self.setting = setting
20
+ self.args = args
21
+ self.device = args.device
22
+ # pass data for initialization
23
+
24
+ @verbose_time_memory
25
+ def reduce(self, data, verbose=True, save=True):
26
+
27
+ args = self.args
28
+ # setting = self.setting
29
+ # device = self.device
30
+
31
+ cpu_data = copy.deepcopy(data)
32
+
33
+ if args.setting == 'trans':
34
+ gps_graph = graphs.Graph(W=data.adj_full)
35
+ candidate, C_list, Gc_list = self.coarsening(gps_graph)
36
+ coarsen_features, coarsen_train_labels, coarsen_train_mask, coarsen_edge = self.process_coarsened(
37
+ cpu_data, candidate, C_list, Gc_list)
38
+
39
+ train_idx = np.nonzero(coarsen_train_mask.numpy())[0]
40
+ coarsen_features = coarsen_features[train_idx]
41
+ coarsen_edge = ei2csr(coarsen_edge, coarsen_train_mask.shape[0])[np.ix_(train_idx, train_idx)]
42
+ coarsen_train_labels = coarsen_train_labels[train_idx]
43
+ else:
44
+ gps_graph = graphs.Graph(W=data.adj_full)
45
+ candidate, C_list, Gc_list = self.coarsening(gps_graph)
46
+ coarsen_features, coarsen_train_labels, coarsen_train_mask, coarsen_edge = self.process_coarsened(
47
+ cpu_data, candidate, C_list, Gc_list)
48
+
49
+ coarsen_edge = ei2csr(coarsen_edge, coarsen_train_mask.shape[0])
50
+
51
+ data.adj_syn, data.feat_syn, data.labels_syn = to_tensor(coarsen_edge), coarsen_features, coarsen_train_labels
52
+ if save:
53
+ save_reduced(data.adj_syn, data.feat_syn, data.labels_syn, args)
54
+
55
+ return data
56
+
57
+ # all_acc = []
58
+
59
+ # for i in trange(args.runs):
60
+ # seed_everything(args.seed + i)
61
+ # coarsen_features, coarsen_train_labels, coarsen_train_mask, coarsen_val_labels, coarsen_val_mask, coarsen_edge = self.process_coarsened(
62
+ # cpu_data, candidate, C_list, Gc_list)
63
+ # coarsen_features = coarsen_features.to(device)
64
+ # if args.save:
65
+ # save_reduced(coarsen_edge, coarsen_features, coarsen_train_labels, args)
66
+ # coarsen_train_labels = coarsen_train_labels.to(device)
67
+ # coarsen_train_mask = coarsen_train_mask.to(device)
68
+ # coarsen_val_labels = coarsen_val_labels.to(device)
69
+ # coarsen_val_mask = coarsen_val_mask.to(device)
70
+ # coarsen_edge = SparseTensor(row=coarsen_edge[1], col=coarsen_edge[0]).to(device)
71
+ # # data = splits(data, args.split)
72
+ #
73
+ # if args.normalize_features:
74
+ # coarsen_features = F.normalize(coarsen_features, p=1)
75
+ # data.x = F.normalize(data.x, p=1)
76
+ #
77
+ # model.reset_parameters()
78
+ # optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
79
+ #
80
+ # best_val_loss = float('inf')
81
+ # val_loss_history = []
82
+ # data.x, data.sparse_adj, data.y = to_tensor(data.x, data.sparse_adj, data.y,
83
+ # device=device)
84
+ # # 这里可以再封装
85
+ # model.fit_with_val(coarsen_features, coarsen_edge, data,
86
+ # train_iters=args.epochs, normalize=True, verbose=False, reindexed_trainset=True)
87
+ # acc_test = model.test(data)
88
+ # res.append(acc_test)
89
+ #
90
+ # for epoch in range(args.epochs):
91
+ #
92
+ # model.train()
93
+ # optimizer.zero_grad()
94
+ # out = model(coarsen_features, coarsen_edge)
95
+ # loss = F.nll_loss(out[coarsen_train_mask], coarsen_train_labels[coarsen_train_mask])
96
+ # loss.backward()
97
+ # optimizer.step()
98
+ #
99
+ # model.eval()
100
+ # pred = model(coarsen_features, coarsen_edge)
101
+ # val_loss = F.nll_loss(pred[coarsen_val_mask], coarsen_val_labels[coarsen_val_mask]).item()
102
+ #
103
+ # if val_loss < best_val_loss:
104
+ # best_val_loss = val_loss
105
+ # pred = model(data.x, data.sparse_adj).max(1)[1]
106
+ # test_acc = int(pred[data.test_mask].eq(data.y[data.test_mask]).sum().item()) / int(
107
+ # data.test_mask.sum())
108
+ # all_acc.append(test_acc)
109
+ #
110
+ # # val_loss_history.append(val_loss)
111
+ # if args.early_stopping > 0:
112
+ # tmp = tensor(val_loss_history[-(args.early_stopping + 1):-1])
113
+ # if val_loss > tmp.mean().item():
114
+ # break
115
+ #
116
+ # print('ave_test_acc: {:.4f}'.format(np.mean(all_acc)), '+/- {:.4f}'.format(np.std(all_acc)))
117
+
118
+ def coarsening(self, H):
119
+ if H.A.shape[-1] != H.A.shape[1]:
120
+ H.logger.error('Inconsistent shape to extract components. '
121
+ 'Square matrix required.')
122
+ return None
123
+
124
+ if H.is_directed():
125
+ raise NotImplementedError('Directed graphs not supported yet.')
126
+
127
+ graphs = []
128
+
129
+ visited = np.zeros(H.A.shape[-1], dtype=bool)
130
+
131
+ while not visited.all():
132
+ stack = set([np.nonzero(~visited)[0][0]])
133
+ comp = []
134
+
135
+ while len(stack):
136
+ v = stack.pop()
137
+ if not visited[v]:
138
+ comp.append(v)
139
+ visited[v] = True
140
+
141
+ stack.update(set([idx for idx in H.A[v, :].nonzero()[1]
142
+ if not visited[idx]]))
143
+
144
+ comp = sorted(comp)
145
+ G = H.subgraph(comp)
146
+ G.info = {'orig_idx': comp}
147
+ graphs.append(G)
148
+
149
+ print('the number of subgraphs is', len(graphs))
150
+ candidate = sorted(graphs, key=lambda x: len(x.info['orig_idx']), reverse=True)
151
+ number = 0
152
+ C_list = []
153
+ Gc_list = []
154
+ while number < len(candidate):
155
+ H = candidate[number]
156
+ if len(H.info['orig_idx']) > 10:
157
+ C, Gc, Call, Gall = self.coarsen(H)
158
+ C_list.append(C)
159
+ Gc_list.append(Gc)
160
+ number += 1
161
+ return candidate, C_list, Gc_list
162
+
163
+ def process_coarsened(self, data, candidate, C_list, Gc_list):
164
+ train_mask = data.train_mask
165
+ val_mask = data.val_mask
166
+
167
+ n_classes = max(data.y) + 1
168
+ if self.args.setting == 'trans':
169
+ features = data.x
170
+ labels = data.y
171
+ else:
172
+ features = data.x[train_mask]
173
+ labels = data.y[train_mask]
174
+ coarsen_node = 0
175
+ number = 0
176
+ coarsen_row = None
177
+ coarsen_col = None
178
+ coarsen_features = torch.Tensor([])
179
+ coarsen_train_labels = torch.Tensor([])
180
+ coarsen_train_mask = torch.Tensor([]).bool()
181
+
182
+ while number < len(candidate):
183
+ H = candidate[number]
184
+ keep = H.info['orig_idx']
185
+ H_features = features[keep]
186
+ H_labels = labels[keep]
187
+ if self.args.setting == "trans":
188
+ H_train_mask = train_mask[keep]
189
+ else:
190
+ H_train_mask = torch.ones(size=(len(H_labels),))
191
+
192
+ if len(H.info['orig_idx']) > 10 and torch.sum(H_train_mask) > 0:
193
+ train_labels = one_hot(H_labels, n_classes) # Shape: (H_labels.shape[0], n_classes)
194
+ if self.args.setting == "trans":
195
+ train_labels[~H_train_mask] = torch.Tensor([0 for _ in range(n_classes)])
196
+ C = C_list[number]
197
+ Gc = Gc_list[number]
198
+
199
+ new_train_mask = torch.BoolTensor(np.sum(C.dot(train_labels), axis=1))
200
+ mix_label = torch.FloatTensor(C.dot(train_labels))
201
+ mix_label[mix_label > 0] = 1
202
+ mix_mask = torch.sum(mix_label, dim=1)
203
+ new_train_mask[mix_mask > 1] = False
204
+
205
+ coarsen_features = torch.cat([coarsen_features, torch.FloatTensor(C.dot(H_features))], dim=0)
206
+ coarsen_train_labels = torch.cat(
207
+ [coarsen_train_labels, torch.argmax(torch.FloatTensor(C.dot(train_labels)), dim=1).float()], dim=0)
208
+ coarsen_train_mask = torch.cat([coarsen_train_mask, new_train_mask], dim=0)
209
+
210
+ if coarsen_row is None:
211
+ coarsen_row = Gc.W.tocoo().row
212
+ coarsen_col = Gc.W.tocoo().col
213
+ else:
214
+ current_row = Gc.W.tocoo().row + coarsen_node
215
+ current_col = Gc.W.tocoo().col + coarsen_node
216
+ coarsen_row = np.concatenate([coarsen_row, current_row], axis=0)
217
+ coarsen_col = np.concatenate([coarsen_col, current_col], axis=0)
218
+ coarsen_node += Gc.W.shape[0]
219
+ print(coarsen_node)
220
+
221
+ # elif torch.sum(H_train_mask) > 0:
222
+ #
223
+ # coarsen_features = torch.cat([coarsen_features, H_features], dim=0)
224
+ # coarsen_train_labels = torch.cat([coarsen_train_labels, H_labels.float()], dim=0)
225
+ # coarsen_train_mask = torch.cat([coarsen_train_mask, H_train_mask], dim=0)
226
+ #
227
+ # if coarsen_row is None:
228
+ # raise Exception('The graph does not need coarsening.')
229
+ # else:
230
+ # if len(H.W.tocoo().row) == 0:
231
+ # current_row = np.array([coarsen_node])
232
+ # current_col = np.array([coarsen_node])
233
+ # else:
234
+ # current_row = H.W.tocoo().row + coarsen_node
235
+ # current_col = H.W.tocoo().col + coarsen_node
236
+ # coarsen_row = np.concatenate([coarsen_row, current_row], axis=0)
237
+ # coarsen_col = np.concatenate([coarsen_col, current_col], axis=0)
238
+ # coarsen_node += H.W.shape[0]
239
+ number += 1
240
+
241
+ # print('the size of coarsen graph features:', coarsen_features.shape)
242
+
243
+ coarsen_edge = torch.from_numpy(np.array([coarsen_row, coarsen_col])).long()
244
+ coarsen_train_labels = coarsen_train_labels.long()
245
+
246
+ return coarsen_features, coarsen_train_labels, coarsen_train_mask, coarsen_edge