/
initialization.py
277 lines (208 loc) · 7.43 KB
/
initialization.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
import numpy as np
import scipy.sparse as sp
from sklearn.decomposition import PCA
from sklearn.utils import check_random_state
from openTSNE import utils
def rescale(x, inplace=False, target_std=1e-4):
"""Rescale an embedding so optimization will not have convergence issues.
Parameters
----------
x: np.ndarray
inplace: bool
target_std: float
Returns
-------
np.ndarray
A scaled-down version of ``x``.
"""
if not inplace:
x = np.array(x, copy=True)
x /= np.std(x[:, 0]) / target_std
return x
def jitter(x, inplace=False, scale=0.01, random_state=None):
"""Add jitter with small standard deviation to avoid numerical problems
when the points overlap exactly.
Parameters
----------
x: np.ndarray
inplace: bool
scale: float
random_state: int or np.random.RandomState
Returns
-------
np.ndarray
A jittered version of ``x``.
"""
if not inplace:
x = np.array(x, copy=True)
target_std = np.std(x[:, 0]) * scale
random_state = check_random_state(random_state)
x += random_state.normal(0, target_std, x.shape)
return x
def random(n_samples, n_components=2, random_state=None, verbose=False):
"""Initialize an embedding using samples from an isotropic Gaussian.
Parameters
----------
n_samples: Union[int, np.ndarray]
The number of samples. Also accepts a data matrix.
n_components: int
The dimension of the embedding space.
random_state: Union[int, RandomState]
If the value is an int, random_state is the seed used by the random
number generator. If the value is a RandomState instance, then it will
be used as the random number generator. If the value is None, the random
number generator is the RandomState instance used by `np.random`.
verbose: bool
Returns
-------
initialization: np.ndarray
"""
random_state = check_random_state(random_state)
if isinstance(n_samples, np.ndarray):
n_samples = n_samples.shape[0]
embedding = random_state.normal(0, 1e-4, (n_samples, n_components))
return np.ascontiguousarray(embedding)
def pca(
X,
n_components=2,
svd_solver="auto",
random_state=None,
verbose=False,
add_jitter=True,
):
"""Initialize an embedding using the top principal components.
Parameters
----------
X: np.ndarray
The data matrix.
n_components: int
The dimension of the embedding space.
svd_solver: str
See sklearn.decomposition.PCA documentation.
random_state: Union[int, RandomState]
If the value is an int, random_state is the seed used by the random
number generator. If the value is a RandomState instance, then it will
be used as the random number generator. If the value is None, the random
number generator is the RandomState instance used by `np.random`.
verbose: bool
add_jitter: bool
If True, jitter with small standard deviation is added to the
initialization to prevent points overlapping exactly, which may lead to
numerical issues during optimization.
Returns
-------
initialization: np.ndarray
"""
timer = utils.Timer("Calculating PCA-based initialization...", verbose)
timer.__enter__()
pca_ = PCA(
n_components=n_components, svd_solver=svd_solver, random_state=random_state
)
embedding = pca_.fit_transform(X)
rescale(embedding, inplace=True)
if add_jitter:
jitter(embedding, inplace=True, random_state=random_state)
timer.__exit__()
return np.ascontiguousarray(embedding)
def spectral(
A,
n_components=2,
tol=1e-4,
max_iter=None,
random_state=None,
verbose=False,
add_jitter=True,
):
"""Initialize an embedding using the spectral embedding of the KNN graph.
Specifically, we initialize data points by computing the diffusion map on
the random walk transition matrix of the weighted graph given by the affiniy
matrix.
Parameters
----------
A: Union[sp.csr_matrix, sp.csc_matrix, ...]
The graph adjacency matrix.
n_components: int
The dimension of the embedding space.
tol: float
See scipy.sparse.linalg.eigsh documentation.
max_iter: float
See scipy.sparse.linalg.eigsh documentation.
random_state: Any
If the value is an int, random_state is the seed used by the random
number generator. If the value is a RandomState instance, then it will
be used as the random number generator. If the value is None, the random
number generator is the RandomState instance used by `np.random`.
add_jitter: bool
If True, jitter with small standard deviation is added to the
initialization to prevent points overlapping exactly, which may lead to
numerical issues during optimization.
verbose: bool
Returns
-------
initialization: np.ndarray
"""
if A.ndim != 2:
raise ValueError("The graph adjacency matrix must be a 2-dimensional matrix.")
if A.shape[0] != A.shape[1]:
raise ValueError("The graph adjacency matrix must be a square matrix.")
timer = utils.Timer("Calculating spectral initialization...", verbose)
timer.__enter__()
D = sp.diags(np.ravel(np.sum(A, axis=1)))
# Find leading eigenvectors
k = n_components + 1
# v0 initializatoin is taken from sklearn.utils._arpack._init_arpack_v0()
random_state = check_random_state(random_state)
v0 = random_state.uniform(-1, 1, A.shape[0])
eigvals, eigvecs = sp.linalg.eigsh(
A, M=D, k=k, tol=tol, maxiter=max_iter, which="LM", v0=v0
)
# Sort the eigenvalues in decreasing order
order = np.argsort(eigvals)[::-1]
eigvecs = eigvecs[:, order]
# In diffusion maps, we multiply the eigenvectors by their eigenvalues
eigvecs *= eigvals
# Drop the leading eigenvector
embedding = eigvecs[:, 1:]
rescale(embedding, inplace=True)
if add_jitter:
jitter(embedding, inplace=True, random_state=random_state)
timer.__exit__()
return embedding
def weighted_mean(X, embedding, neighbors, distances, verbose=False):
"""Initialize points onto an existing embedding by placing them in the
weighted mean position of their nearest neighbors on the reference embedding.
Parameters
----------
X: np.ndarray
embedding: TSNEEmbedding
neighbors: np.ndarray
distances: np.ndarray
verbose: bool
Returns
-------
np.ndarray
"""
n_samples = X.shape[0]
n_components = embedding.shape[1]
with utils.Timer("Calculating weighted-mean initialization...", verbose):
partial_embedding = np.zeros((n_samples, n_components), order="C")
for i in range(n_samples):
partial_embedding[i] = np.average(
embedding[neighbors[i]], axis=0, weights=distances[i]
)
return partial_embedding
def median(embedding, neighbors, verbose=False):
"""Initialize points onto an existing embedding by placing them in the
median position of their nearest neighbors on the reference embedding.
Parameters
----------
embedding: TSNEEmbedding
neighbors: np.ndarray
verbose: bool
Returns
-------
np.ndarray
"""
with utils.Timer("Calculating meadian initialization...", verbose):
embedding = np.median(embedding[neighbors], axis=1)
return np.ascontiguousarray(embedding)