-
Notifications
You must be signed in to change notification settings - Fork 0
/
synthetic_data.py
417 lines (343 loc) · 12.9 KB
/
synthetic_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def _shuffle(data, random_state=None):
generator = check_random_state(random_state)
n_rows, n_cols = data.shape
row_idx = generator.permutation(n_rows)
col_idx = generator.permutation(n_cols)
result = data[row_idx][:, col_idx]
return result, row_idx, col_idx
import numbers
import array
import warnings
from collections.abc import Iterable
import numpy as np
from scipy import linalg
import scipy.sparse as sp
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.utils import check_array, check_random_state
from sklearn.utils import shuffle as util_shuffle
from sklearn.utils.random import sample_without_replacement
def make_biclusters(
shape,
n_clusters,
a=None,
b=None,
*,
noise=0.0,
minval=10,
maxval=100,
shuffle=True,
random_state=None,
):
"""Generate a constant block diagonal structure array for biclustering.
Read more in the :ref:`User Guide <sample_generators>`.
Parameters
----------
shape : iterable of shape (n_rows, n_cols)
The shape of the result.
n_clusters : int
The number of biclusters.
noise : float, default=0.0
The standard deviation of the gaussian noise.
minval : int, default=10
Minimum value of a bicluster.
maxval : int, default=100
Maximum value of a bicluster.
shuffle : bool, default=True
Shuffle the samples.
random_state : int, RandomState instance or None, default=None
Determines random number generation for dataset creation. Pass an int
for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Returns
-------
X : ndarray of shape `shape`
The generated array.
rows : ndarray of shape (n_clusters, X.shape[0])
The indicators for cluster membership of each row.
cols : ndarray of shape (n_clusters, X.shape[1])
The indicators for cluster membership of each column.
See Also
--------
make_checkerboard: Generate an array with block checkerboard structure for
biclustering.
References
----------
.. [1] Dhillon, I. S. (2001, August). Co-clustering documents and
words using bipartite spectral graph partitioning. In Proceedings
of the seventh ACM SIGKDD international conference on Knowledge
discovery and data mining (pp. 269-274). ACM.
"""
generator = check_random_state(random_state)
n_rows, n_cols = shape
consts = generator.uniform(minval, maxval, n_clusters)
# row and column clusters of approximately equal sizes
if a is None and b is None:
a = np.repeat(1.0 / n_clusters, n_clusters)
b = np.repeat(1.0 / n_clusters, n_clusters)
row_sizes = generator.multinomial(n_rows, a)
col_sizes = generator.multinomial(n_cols, b)
row_labels = np.hstack(
list(np.repeat(val, rep) for val, rep in zip(range(n_clusters), row_sizes))
)
col_labels = np.hstack(
list(np.repeat(val, rep) for val, rep in zip(range(n_clusters), col_sizes))
)
result = np.zeros(shape, dtype=np.float64)
for i in range(n_clusters):
selector = np.outer(row_labels == i, col_labels == i)
result[selector] += consts[i]
if noise > 0:
result += generator.normal(scale=noise, size=result.shape)
if shuffle:
result, row_idx, col_idx = _shuffle(result, random_state)
row_labels = row_labels[row_idx]
col_labels = col_labels[col_idx]
rows = np.vstack([row_labels == c for c in range(n_clusters)])
cols = np.vstack([col_labels == c for c in range(n_clusters)])
return result, rows, cols
def make_checkerboard(
shape,
n_clusters,
a=None,
b=None,
*,
noise=0.0,
minval=10,
maxval=100,
shuffle=True,
random_state=None,
):
"""Generate an array with block checkerboard structure for biclustering.
Read more in the :ref:`User Guide <sample_generators>`.
Parameters
----------
shape : tuple of shape (n_rows, n_cols)
The shape of the result.
n_clusters : int or array-like or shape (n_row_clusters, n_column_clusters)
The number of row and column clusters.
noise : float, default=0.0
The standard deviation of the gaussian noise.
minval : int, default=10
Minimum value of a bicluster.
maxval : int, default=100
Maximum value of a bicluster.
shuffle : bool, default=True
Shuffle the samples.
random_state : int, RandomState instance or None, default=None
Determines random number generation for dataset creation. Pass an int
for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Returns
-------
X : ndarray of shape `shape`
The generated array.
rows : ndarray of shape (n_clusters, X.shape[0])
The indicators for cluster membership of each row.
cols : ndarray of shape (n_clusters, X.shape[1])
The indicators for cluster membership of each column.
See Also
--------
make_biclusters : Generate an array with constant block diagonal structure
for biclustering.
References
----------
.. [1] Kluger, Y., Basri, R., Chang, J. T., & Gerstein, M. (2003).
Spectral biclustering of microarray data: coclustering genes
and conditions. Genome research, 13(4), 703-716.
"""
generator = check_random_state(random_state)
if hasattr(n_clusters, "__len__"):
n_row_clusters, n_col_clusters = n_clusters
else:
n_row_clusters = n_col_clusters = n_clusters
# row and column clusters of approximately equal sizes
n_rows, n_cols = shape
if a is None and b is None:
a = np.repeat(1.0 / n_clusters, n_clusters)
b = np.repeat(1.0 / n_clusters, n_clusters)
row_sizes = generator.multinomial(n_rows, a)
col_sizes = generator.multinomial(n_cols, b)
row_labels = np.hstack(
list(np.repeat(val, rep) for val, rep in zip(range(n_row_clusters), row_sizes))
)
col_labels = np.hstack(
list(np.repeat(val, rep) for val, rep in zip(range(n_col_clusters), col_sizes))
)
result = np.zeros(shape, dtype=np.float64)
for i in range(n_row_clusters):
for j in range(n_col_clusters):
selector = np.outer(row_labels == i, col_labels == j)
result[selector] += generator.uniform(minval, maxval)
if noise > 0:
result += generator.normal(scale=noise, size=result.shape)
if shuffle:
result, row_idx, col_idx = _shuffle(result, random_state)
row_labels = row_labels[row_idx]
col_labels = col_labels[col_idx]
rows = np.vstack(
[
row_labels == label
for label in range(n_row_clusters)
for _ in range(n_col_clusters)
]
)
cols = np.vstack(
[
col_labels == label
for _ in range(n_row_clusters)
for label in range(n_col_clusters)
]
)
return result, rows, cols
import scipy.sparse as sp
from gcc.utils import read_dataset, preprocess_dataset
from sklearn.metrics import silhouette_score, davies_bouldin_score
def A():
n_classes = 10
features, rows, cols = make_biclusters((500, 500), n_classes,
noise=30.0, minval=10, maxval=100,
shuffle=True,
random_state=0)
return features, rows, cols, n_classes, 'A', None, None
def B():
n_classes = 6
r=[2,25,3, 5, 10, 1];r=np.array(r)/sum(r)
c=[2,10,33,32, 6, 10];c=np.array(c)/sum(c)
features, rows, cols = make_biclusters((800, 1000), n_classes,
noise=40.0, minval=10, maxval=100,
shuffle=True,
random_state=0,
a=r,b=c)
return features, rows, cols, n_classes, 'B', r, c
def C():
n_classes = 8
features, rows, cols = make_checkerboard((800, 800), n_classes,
noise=40.0, minval=10, maxval=100,
shuffle=True,
random_state=0)
return features, rows, cols, n_classes, 'C', None, None
def D():
n_classes = 7
r=[1,.05,.1,.2,1,.5,1];r=np.array(r)/sum(r)
c=[.2,.1,.25,1,1,.5,1];c=np.array(c)/sum(c)
features, rows, cols = make_checkerboard((2000, 1200), n_classes,
noise=40.0, minval=10, maxval=100,
shuffle=True,
random_state=0,
a=r,b=c)
return features, rows, cols, n_classes, 'D', r, c
def E():
n_classes = 15
r=[ 7, 1, 2, 8, 5, 19, 4, 7, 18, 9, 5, 17, 18, 9, 16];r=np.array(r)/sum(r)
c=[ 6, 19, 18, 12, 12, 10, 13, 19, 14, 3, 10, 7, 16, 15, 10];c=np.array(c)/sum(c)
features, rows, cols = make_biclusters((2500, 1500), n_classes,
noise=40.0, minval=10, maxval=100,
shuffle=True,
random_state=0,
a=r,b=c)
return features, rows, cols, n_classes, 'E', r, c
%cd /content/gcc
from sklearn.utils.extmath import randomized_svd
from time import time
import tensorflow as tf
import numpy as np
from gcc.metrics import output_metrics, print_metrics
from gcc.utils import read_dataset, preprocess_dataset
from sklearn.kernel_approximation import RBFSampler, PolynomialCountSketch, Nystroem
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.neighbors import kneighbors_graph
from time import time
from scipy import sparse
from sklearn.metrics import silhouette_score
import tensorflow as tf
def pmi(df, positive=True):
col_totals = df.sum(axis=0)
total = col_totals.sum()
row_totals = df.sum(axis=1)
expected = np.outer(row_totals, col_totals) / total
df = df / expected
# Silence distracting warnings about log(0):
with np.errstate(divide='ignore'):
df = np.log(df)
df[~np.isfinite(df)] = 0.0 # log(0) = 0
if positive:
df[df < 0] = 0.0
return df
def average_pmi_per_cluster(x, labels):
values = 0
pmi_mat = pmi(x @ x.T, positive=False)
for c in np.unique(labels):
intra = pmi_mat[labels == c][:, labels == c]
inter = pmi_mat[labels == c][:, labels != c]
v = np.mean(intra) - np.mean(inter)
values += v * np.sum(labels == c) / len(labels)
return values
@tf.function
def convolve(feature, adj_normalized, power):
for _ in range(power):
feature = tf.sparse.sparse_dense_matmul(adj_normalized, feature)
return feature
n_runs = 5
n_runs = 10
n_clusters = 0
p = 10
for dataset in [A(), B(), C(), D(), E()]:
n_runs = 10
features, rows, cols,n_classes, name, r, c = dataset
adj = kneighbors_graph(features, 3, mode='connectivity')
rows, cols = rows.argmax(0), cols.argmax(0)
n, d = features.shape
k = n_classes
metrics = {}
metrics['time'] = []
metrics['acc'] = []
metrics['nmi'] = []
metrics['ari'] = []
metrics['cos'] = []
# print(dataset, '-----------')
tf_idf = True
n, d = features.shape
norm_adj, features = preprocess_dataset(adj, features,
tf_idf=tf_idf,
sparse=False)
ppmi_mat = ppmi(features)
y_indices = np.argsort(ppmi_mat)[:, :top_n].reshape(-1)
x_indices = np.repeat(np.arange(d), top_n)
values = np.sort(ppmi_mat)[:, :top_n].reshape(-1)
ppmi_mat = sparse.csr_matrix((values, (x_indices, y_indices)), shape=(d,d))
col_norm_adj, _ = preprocess_dataset(ppmi_mat, features,
tf_idf=tf_idf,
sparse=False)
n, d = features.shape
k = n_classes
metrics = {}
metrics['pmi'] = []
metrics['acc'] = []
metrics['nmi'] = []
metrics['ari'] = []
metrics['time'] = []
def convert_sparse_matrix_to_sparse_tensor(X):
coo = X.tocoo()
indices = np.mat([coo.row, coo.col]).transpose()
return tf.SparseTensor(indices, coo.data, coo.shape)
norm_adj = convert_sparse_matrix_to_sparse_tensor(norm_adj.astype('float64'))
features = tf.convert_to_tensor(features.astype('float64'))
x = features
for run in range(n_runs):
features = x
t0 = time()
features = features @ col_norm_adj
features = convolve(features, norm_adj, p)
P, _, Q, _ = run_model(features, c=2**-.5, k=k, coclustering=True)
metrics['time'].append(time()-t0)
a = clustering_accuracy(rows, P)
b = clustering_accuracy(cols, Q)
metrics['acc'].append((a+b-a*b)*100)
results = {
'mean': {k:(np.mean(v)).round(2) for k,v in metrics.items() },
'std': {k:(np.std(v)).round(2) for k,v in metrics.items()}
}
means = results['mean']
std = results['std']
print(f"{name} {p}")
print(f"{means['acc']}±{std['acc']}", sep=',')