-
Notifications
You must be signed in to change notification settings - Fork 1
/
kmeans_radec.py
379 lines (301 loc) · 9.67 KB
/
kmeans_radec.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
"""
k means on the sphere
Adapted from this stack overflow answer
http://stackoverflow.com/questions/5529625/is-it-possible-to-specify-your-own-distance-function-using-scikit-learn-k-means
"""
from __future__ import print_function
from __future__ import division
import random
import numpy
_TOL_DEF=1.0e-5
_MAXITER_DEF=100
_VERBOSE_DEF=1
class KMeans(object):
"""
A class to perform K-means on the input ra,dec using spherical distances
parameters
----------
centers_guess: array
[ncen, ra, dec] starting guesses. Can reset later with set_centers()
tol: float, optional
The relative change in the average distance to
centers, signifies convergence
verbose: int, optional
How verbose. 0 silent, 1 minimal starting info, 2 prints running
distances
attributes after running
------------------------
.converged: bool
True if converged
.centers: array
the found centers
.labels: array
[N,ra,dec] array
.distances: array
Distance from each point to each center
.X: array
The data that was processed
example
-------
import kmeans_radec
from kmeans_radec import KMeans
cen_guess=numpy.zeros( (ncen, 2) )
cen_guess[:,0] = ra_guesses
cen_guess[:,1] = dec_guesses
km=KMeans(cen_guess)
km.run(X, maxiter=100)
# did it converge?
if not km.converged:
# did not converge. This might be ok, but if we want
# to run more we can
km.run(X, maxiter=maxiter)
# or we could try a different set of center guesses...
km.set_centers(cen_guess2)
km.run(X, maxiter=100)
# results are saved in attributes
print(km.centers, km.labels, km.distances)
print("copy of centers:",km.get_centers())
# once we have our centers, we can identify to which cluster
# a *different* set of points belong. This could be a set
# of random points we want to associate with the same regions
labels=km.find_nearest(X2)
# you can save the centers and load them into a KMeans
# object at a later time
km=KMeans(centers)
labels=km.find_nearest(X)
"""
def __init__(self, centers,
tol=_TOL_DEF,
verbose=_VERBOSE_DEF):
self.set_centers(centers)
self.tol=float(tol)
self.verbose=verbose
def run(self, X, maxiter=_MAXITER_DEF):
"""
run k means, either until convergence is reached or the indicated
number of iterations are performed
parameters
----------
X: array
[N, ra, dec] array
maxiter: int, optional
Max number of iterations to run.
"""
centers=self.get_centers()
_check_dims(X, self.centers)
N, dim = X.shape
ncen, cdim = centers.shape
if self.verbose:
tup=(X.shape, centers.shape, self.tol, maxiter)
print("X %s centers %s tol=%.2g maxiter=%d" % tup)
self.converged=False
allx = numpy.arange(N)
prevdist = 0
for jiter in xrange( 1, maxiter+1 ):
D = cdist_radec(X, centers) # npoints x ncenters
labels = D.argmin(axis=1) # X -> nearest centre
distances = D[allx,labels]
avdist = distances.mean() # median ?
if self.verbose >= 2:
print(" av |X - nearest centre| = %.4g" % avdist)
self.converged = (1 - self.tol) * prevdist <= avdist <= prevdist
if self.converged:
break
if jiter==maxiter:
break
prevdist = avdist
for jc in range(ncen): # (1 pass in C)
c, = numpy.where( labels == jc )
if len(c) > 0:
centers[jc] = X[c].mean( axis=0 )
if self.verbose:
print(jiter,"iterations cluster "
"sizes:", numpy.bincount(labels))
if self.verbose >= 2:
self._print_info()
self.X=X
self.centers=centers
self.labels=labels
self.distances=distances
def set_centers(self, centers):
"""
set starting centers
parameters
----------
centers: array
[Ncen] array of centers
"""
centers=numpy.asanyarray(centers)
# we won't change this
self.centers_guess=centers.copy()
# this will evolve during the run
self.centers=centers.copy()
def get_centers(self):
"""
get a copy of the centers
"""
centers=self.centers
if centers is None:
raise ValueError("you must set centers first")
return centers.copy()
def find_nearest(self, X):
"""
find the nearest centers to the input points
"""
return find_nearest(X, self.centers)
def _print_info(self):
ncen=self.centers.size
r50 = numpy.zeros(ncen)
r90 = numpy.zeros(ncen)
distances=self.distances
labels=self.labels
for j in range(ncen):
dist = distances[ labels == j ]
if len(dist) > 0:
r50[j], r90[j] = numpy.percentile( dist, (50, 90) )
print("kmeans: cluster 50 % radius", r50.astype(int))
print("kmeans: cluster 90 % radius", r90.astype(int))
# scale L1 / dim, L2 / sqrt(dim) ?
def kmeans(X, centers_guess,
tol=_TOL_DEF,
maxiter=_MAXITER_DEF,
verbose=_VERBOSE_DEF):
"""
perform kmeans on the input ra,dec using spherical distances
parameters
----------
X: array
[N, ra, dec] array
centers_guess: array
[ncen, ra, dec] array. The center guesses.
tol: float, optional
The relative change in the average distance to
centers, signifies convergence
verbose: int, optional
How verbose. 0 silent, 1 minimal starting info, 2 prints running
distances
returns
-------
A KMeans object, with attributes .centers, .labels, .distances etc.
.converged: bool
True if converged
.centers: array
The array of centers, [ncen, ra, dec]
.labels: array
The index of the center closest to each input point [N]
.distances: array
The distance to the closest center for each poit [N]
"""
km=KMeans(centers_guess, tol=tol, verbose=verbose)
km.run(X, maxiter=maxiter)
return km
def kmeans_sample(X, ncen, nsample=None, maxiter=_MAXITER_DEF, **kw ):
"""
2-pass kmeans, fast for large N
- kmeans a smaller random sample from X
- take starting guesses for the centers from a random sample
of the input points
- full kmeans, starting from the centers from pass 1
parameters
----------
X: array
[N, ra, dec] array
ncen: int
Number of centers
nsample: int, optional
Number of samples to use on first pass, default
max( 2*sqrt(N), 10*ncen )
tol: float, optional
The relative change in the average distance to
centers, signifies convergence
verbose: int, optional
How verbose. 0 silent, 1 minimal starting info, 2 prints running
distances
returns
-------
A KMeans object, with attributes .centers, .labels, .distances etc.
.converged: bool
True if converged
.centers: array
The array of centers, [ncen, ra, dec]
.labels: array
The index of the center closest to each input point [N]
.distances: array
The distance to the closest center for each poit [N]
"""
N, dim = X.shape
if nsample is None:
nsample = max( 2*numpy.sqrt(N), 10*ncen )
# smaller random sample to start with
Xsample = random_sample( X, int(nsample) )
# choose random sample as centers
pass1centers = random_sample( X, int(ncen) )
km=KMeans(pass1centers, **kw)
km.run(Xsample, maxiter=maxiter)
# now a full run with these centers
sample_centers = km.get_centers()
km=KMeans(sample_centers, **kw)
km.run(X, maxiter=maxiter)
return km
_PIOVER2=numpy.pi*0.5
def cdist_radec(a1, a2):
"""
use broadcasting to get all distance pairs
a represents [N,ra,dec]
"""
from numpy import cos, sin, arccos, newaxis, deg2rad
ra1=a1[:,0]
dec1=a1[:,1]
ra2=a2[:,0]
dec2=a2[:,1]
ra1=ra1[:,newaxis]
dec1=dec1[:,newaxis]
phi1 = deg2rad(ra1)
theta1 = _PIOVER2 - deg2rad(dec1)
phi2 = deg2rad(ra2)
theta2 = _PIOVER2 - deg2rad(dec2)
sintheta = sin(theta1)
x1 = sintheta * cos(phi1)
y1 = sintheta * sin(phi1)
z1 = cos(theta1)
sintheta = sin(theta2)
x2 = sintheta * cos(phi2)
y2 = sintheta * sin(phi2)
z2 = cos(theta2)
costheta = x1*x2 + y1*y2 + z1*z2
costheta=numpy.clip(costheta,-1.0,1.0)
theta = arccos(costheta)
return theta
def random_sample( X, n ):
"""
random.sample of the rows of X
"""
sampleix = random.sample( xrange( X.shape[0] ), int(n) )
return X[sampleix]
def find_nearest( X, centers):
"""
find the nearest center for each input point
parameters
----------
X: array
[N,ra,dec] points
centers: array
[ncen,ra,dec] center points
returns
-------
labels: array
The index of the nearest center for each input point
"""
_check_dims(X, centers)
D = cdist_radec( X, centers) # |X| x |centers|
return D.argmin(axis=1)
def _check_dims(X, centers):
"""
check the dims are compatible
"""
N, dim = X.shape
ncen, cdim = centers.shape
if dim != cdim:
tup=(X.shape, centers.shape )
raise ValueError("X %s and centers %s must have the same "
"number of columns" % tup)