-
Notifications
You must be signed in to change notification settings - Fork 0
/
spectral_clustering.py
306 lines (254 loc) · 9.21 KB
/
spectral_clustering.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
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 09:44:29 2020
@author: Martin Buck
Implement Spectral Clustering
"""
import numpy as np
from scipy.io import loadmat
from scipy.io import savemat
from scipy.spatial.distance import euclidean
import matplotlib.pyplot as plt
import random
import time
import os
# load simple toy data sets to implement spectral clustering on
spiral_mat = loadmat('datasets/spirals.mat')
spiral_data = spiral_mat['X']
# epsilon determines when k-means should stop iterating
epsilon = 10**-16
# need to tune parameter sigma
s_arr = [.001, .01, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1, 10, 100]
# clusters
k = 2
# number of eigenvectors to explore embedding
e_start = 0
e_end = 3
start_time = time.time()
def main():
"""Run the spectral clustering alg. on the above data sets."""
eigen_errors = np.zeros((len(s_arr),))
error_count = 0
for s in s_arr:
folder = 'plots/sigma = ' + str(s) + '/spirals'
if not os.path.isdir(folder):
os.makedirs(folder)
eigen_errors[error_count] = \
spect(spiral_data, 'mat files/spiral_laplacian.mat_' + str(s) +
'.mat', folder, s)
error_count += 1
# plot error as a function of number of eigenvectors included, and error
# as a function of sigma
plt.plot(eigen_errors)
def spect(X, dataset_str, folder, s):
"""Cluster data using eigenvectors of Laplacian and k-means."""
# First center and scale data and plot
X = scale(X)
plot_data(X, folder)
if not os.path.isfile(dataset_str):
L = laplacian(X, folder, dataset_str, s)
else:
laplacian_matrix = loadmat(dataset_str)
L = laplacian_matrix['L']
# Now compute eigenvectors of L
w, v = np.linalg.eig(L)
# order and display eigenvalues and eigenvectors from smallest to largest
ind = np.argsort(w)
# get rid of imaginary parts
if s < .1:
w = np.real(w)
v = np.real(v)
w = w[ind]
v = v[:, ind]
# run k-means on embedded data using the 2nd and 3rd eigenvector
phi_X = v[:, 1:2]
eigen_error = k_means(phi_X, X, 2, folder, s)
return eigen_error
def k_means(X, X_o, e, folder, s):
"""Run k-means on data set X."""
# randomly assign centers. Assume two clusters for now
mu1 = [random.uniform(-.005, .005) for i in range(e)]
mu2 = [random.uniform(-.005, .005) for i in range(e)]
# will store sum of squared 2-norm errors
errors = np.zeros((0,))
error_count = 1
# run k-means twice in order to initialize error condition in while loop
labels, error = label(X, mu1, mu2)
errors = np.append(errors, error)
mu1, mu2 = find_centers(X, labels, e)
# plot labeled embedded data and labeled orginal data
if e < 4:
plot_clusters(X, labels, s, e, 1, error_count, folder)
plot_clusters(X_o, labels, s, e, 0, error_count, folder)
error_count += 1
labels, error = label(X, mu1, mu2)
errors = np.append(errors, error)
mu1, mu2 = find_centers(X, labels, e)
# plot labeled embedded data and labeled orginal data
if e < 4:
plot_clusters(X, labels, s, e, 1, error_count, folder)
plot_clusters(X_o, labels, s, e, 0, error_count, folder)
error_count += 1
for i in range(20):
labels, error = label(X, mu1, mu2)
errors = np.append(errors, error)
mu1, mu2 = find_centers(X, labels, e)
# plot labeled embedded data and labeled original data
if e < 4:
plot_clusters(X, labels, s, e, 1, error_count, folder)
plot_clusters(X_o, labels, s, e, 0, error_count, folder)
error_count += 1
plot_errors(errors, error_count-1, e, folder)
plt.title('Errors vs. Sigma')
plt.xlabel('Sigma')
plt.ylabel('Square Euclidean Error')
plt.xticks(range(14), ['.001', '.01', '.1', '.2', '.3', '.4', '.5', '.6',
'.7', '.8', '.9', '1', '10', '100'])
return errors[-1]
def laplacian(X, folder, dataset_str, s):
"""Create the Laplacian matrix."""
n = np.shape(X)[0]
W = np.zeros((n, n))
D = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
w = gauss(X[i, :], X[j, :], s)
# w = inner(X[i, :], X[j, :], d)
if i != j:
W[i, j] = w
W[j, i] = w
D[i, i] = np.sum(W[i, :])
# Laplacian is the difference of these two matrices
L = D - W
# visualize matrix
plt.figure()
plt.matshow(W)
plt.title('Weight matrix')
plt.savefig(folder + '/' + 'Weight matrix')
plt.show()
savemat(dataset_str, {'L': L})
return L
def label(X, mu1, mu2):
"""Label each data point by its closest center and calculate error."""
# now iterate over all the points in the data set and calculate the
# distance to each center and assign a label to the closer center
n = np.shape(X)[0]
labels = np.zeros((n,))
error = 0
for i in range(n):
x = X[i, :]
d1 = euclidean(x, mu1)**2
d2 = euclidean(x, mu2)**2
if d1 < d2:
labels[i] = 1
error += d1
else:
labels[i] = 2
error += d2
return labels, error
def find_centers(X, labels, e):
"""Find new centers of clusters."""
# now update the means of each cluster
n = np.shape(X)[0]
sum1 = [0 for i in range(e)]
sum2 = [0 for i in range(e)]
count1 = 0
count2 = 0
for i in range(n):
x = X[i, :]
if labels[i] == 1:
sum1 += x
count1 += 1
else:
sum2 += x
count2 += 1
if count1 > 0:
mu1 = sum1/count1
else:
mu1 = [random.uniform(-.005, .005) for i in range(e)]
if count2 > 0:
mu2 = sum2/count2
else:
mu2 = [random.uniform(-.005, .005) for i in range(e)]
return mu1, mu2
def plot_data(X, folder):
"""Plot scaled data to get a feel for what it looks like."""
plt.figure()
plt.scatter(X[:, 0], X[:, 1])
plt.title('Standardized data')
plt.xlabel('x1')
plt.ylabel('x2')
plt.savefig(folder + '/' + 'Standardized data')
plt.show()
def plot_clusters(X, labels, s, e, eigen, error_count, folder):
"""Plot and color code clusters."""
# plot original 2-D clusters with labels from k-means on embedding
if not eigen:
plt.scatter(X[labels == 1, 0], X[labels == 1, 1], c='r')
plt.scatter(X[labels == 2, 0], X[labels == 2, 1], c='b')
plt.title('sigma = ' + str(s) + ', ' + str(e) +
' eigenvector(s), ' +
'iteration ' + str(error_count))
plt.xlabel('x1')
plt.ylabel('x2')
plt.savefig(folder + '/' + str(e) +
' eigenvector(s), ' +
'iteration ' + str(error_count))
plt.show()
# if only using 1 eigenvector, plot embedded data that k-means was
# performed on
elif eigen and len(np.shape(X)) == 1 or np.shape(X)[1] == 1:
y1 = np.zeros((len(X[labels == 1, 0]),))
y2 = np.zeros((len(X[labels == 2, 0]),))
plt.scatter(X[labels == 1, 0], y1, c='r')
plt.scatter(X[labels == 2, 0], y2, c='b')
plt.savefig(folder + '/' + str(e) +
' embedded data, ' +
'iteration ' + str(error_count))
plt.show()
# if only using 2 eigenvectors, plot embedded data that k-means was
# performed on
elif eigen and np.shape(X)[1] == 2:
plt.scatter(X[labels == 1, 0], X[labels == 1, 1], c='r')
plt.scatter(X[labels == 2, 0], X[labels == 2, 1], c='b')
plt.title('sigma = ' + str(s) + ', ' + str(e) +
'eigenvector(s) embedded data, ' +
'iteration ' + str(error_count))
plt.savefig(folder + '/' + str(e) +
'eigenvector(s) embedded data, ' +
'iteration ' + str(error_count))
plt.show()
# if only using 3 eigenvectors, plot embedded data that k-means was
# performed on
elif eigen and np.shape(X)[1] == 3:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[labels == 1, 0], X[labels == 1, 1], X[labels == 1, 2],
c='r')
ax.scatter(X[labels == 2, 0], X[labels == 2, 1], X[labels == 2, 2],
c='b')
plt.savefig(folder + '/' + str(e) +
'eigenvector(s) embedded data, ' +
'iteration ' + str(error_count))
plt.show()
def plot_errors(errors, error_count, e, folder):
"""Plot k-means error as a function of number of iterations."""
plt.plot(range(error_count), errors)
plt.xlabel('Iterations')
plt.ylabel('Squared euclidean error')
plt.title('K-means error vs. iterations')
plt.savefig(folder + '/' + 'K-means error vs iterations, ' + str(e) +
' eigenvectors')
plt.show()
def gauss(x, y, sigma):
"""Calculate the Gaussian kernel."""
return np.exp((-(np.linalg.norm(x-y)**2)/(2*(sigma**2))))
def inner(x, y, d):
"""Calculate the power of dot product kernel."""
return np.dot(x, y)**d
def scale(X):
"""Center and scale data so it is mean zero and unit variance."""
return (X - np.mean(X, axis=0))/np.std(X, axis=0)
if __name__ == "__main__":
main()
print("--- %s seconds ---" % (time.time() - start_time))