-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[python_file]kmeans_pca.py
More file actions
567 lines (451 loc) · 106 KB
/
[python_file]kmeans_pca.py
File metadata and controls
567 lines (451 loc) · 106 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# -*- coding: utf-8 -*-
"""KMeans_PCA.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1YF4Dq0lVyo-iKoSt-dykdsfDIgYf5qEp
You may use the MNIST dataset or any dataset for Face Images or Flower Images for this assignment.
TASK 1) Implement k-means clustering. Analyse the clusters formed for various values of k. Display the centroids of the clusters. DO NOT USE IN_BUILT ROUTINE for k-means clustering.
2) Implement Dimensionality reduction using PCA. Analyse the reconstruction error for various values of k. Display the Eigen Vectors. DO NOT USE IN_BUILT ROUTINE for implementing PCA. However you can use in-built routines for computing Eigen vectors and Eigen values.
Note that when you apply PCA on images, you are dealing with data with a very high dimensionality, i.e. d>m, where m is the number of images in the training dataset. Therefore you need to apply the technique given in Section 23.1.1. of the Textbook.
Further, for images, you have the red, green and blue components for the color at every pixel location. You can simply consider the average of the three color components. This average is the intensity value at the pixel. The feature vector is constructed using the intensity values of the all the pixels in the image.
Prepare a report with all the results and steps of implementation.

# Task 1 :
1. Kmeans clustering
2. Clusters formed for diff K
3. centroids of the clusters
Dissimilar examples should be part of different clusters, Similar examples should be part of same cluster. K means tries to put the data into the number of clusters we tell it to. For a given K, randomly chose k data points to be the initial clyster centers, Assign each data point to each clyster center, Re Compute the cluster centers with previous clustering. If converging criteria does not met repeat again.
K means works through the following iterative process:
Pick a value for k (the number of clusters to create)
Initialize k ‘centroids’ (starting points) in your data
Create your clusters. Assign each point to the nearest centroid.
Make your clusters better. Move each centroid to the center of its cluster.
Repeat steps 3–4 until your centroids converge.
# Using Inbuilt Functions
"""
from sklearn import datasets
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
plt.scatter(X[:,0], X[:,1], c=y, cmap='gist_rainbow')
plt.xlabel('Spea1 Length', fontsize=18)
plt.ylabel('Sepal Width', fontsize=18)
km = KMeans(n_clusters = 3, n_jobs = 4, random_state=21)
km.fit(X)
centers = km.cluster_centers_
print(centers)
new_labels = km.labels_
# Plot the identified clusters and compare with the answers
fig, axes = plt.subplots(1, 2, figsize=(16,8))
axes[0].scatter(X[:, 0], X[:, 1], c=y, cmap='gist_rainbow',edgecolor='k', s=150)
axes[1].scatter(X[:, 0], X[:, 1], c=new_labels, cmap='jet',edgecolor='k', s=150)
axes[0].set_xlabel('Sepal length', fontsize=18)
axes[0].set_ylabel('Sepal width', fontsize=18)
axes[1].set_xlabel('Sepal length', fontsize=18)
axes[1].set_ylabel('Sepal width', fontsize=18)
axes[0].tick_params(direction='in', length=10, width=5, colors='k', labelsize=20)
axes[1].tick_params(direction='in', length=10, width=5, colors='k', labelsize=20)
axes[0].set_title('Actual', fontsize=18)
axes[1].set_title('Predicted', fontsize=18)
"""# Not using Inbuilt Functions"""
from sklearn import datasets
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
plt.scatter(X[:,0], X[:,1], c=y, cmap='gist_rainbow')
plt.xlabel('Spea1 Length', fontsize=18)
plt.ylabel('Sepal Width', fontsize=18)
"""Let us define some basics to start the K means algorithm. There is a Threshold (theta) for movement of centroid in K means, total iterations define the max number of interations that the running algorithm takes place. The train/fit and predict functions will give the functionality of the K Means. The underlying difference between K Means and General Classification algorithms is that, in K Means we just focus whether we achieved the clusters which we targeted however in other clsutering algorithms we focus on more of finding how accurate the algorithm worked. Since it is unsupervised we have to use only training."""
k=4
theta = 0.01
tot_iter = 80
colors = 10*["g", "r", "b", "c", "k"]
def fit(data):
centroids = {}
for i in range(k):
centroids[i]= data[i]
# That is first k=4 centroids will be the starting k=4 of the dataset
for i in range(tot_iter):
labels = {}
for i in range(k):
labels[i] = []
# feature set in data
for fset in X:
distances = [np.linalg.norm(fset-centroids[centroid]) for centroid in centroids]
# Creating a list of distances where 0th element of the list will be
# the distance to the 0th centroid with data elements.
label = distances.index(min(distances)) # Classification
labels[label].append(fset) # Says that feature set belongs to that centroid
prev_centroids = dict(centroids)
for label in labels:
pass
# centroids[label] = np.average(labels[label], axis=0)
# Taking avergae of all the labels we have and assigning the centroid with that label
# Finds the centroid for previous centroids labels
# Finds the mean of all the features for any given class and redefines the centroid
converged = True
for clabel in centroids:
original_centroid = prev_centroids[clabel]
current_centroid = centroids[clabel]
# Checking for the threshold theta by which the centroid should take movements
if np.sum((current_centroid - original_centroid)/original_centroid * 100) > theta:
converged = False
if converged:
break
for centroid in centroids:
plt.scatter(centroids[centroid][0], centroids[centroid][1], marker="o", color="k", s=150, linewidths=5)
for label in labels:
color = colors[label]
for fset in labels[label]:
plt.scatter(fset[0], fset[1], marker="x", color=color, s=150, linewidths=5)
def predict(data):
distances = [np.linalg.norm(data-centroids[centroid]) for centroid in centroids]
label = distances.index(min(distance))
return label
"""# OLD CENTROIDS"""
fit(X)
k=4
theta = 0.01
tot_iter = 80
colors = 10*["g", "r", "b", "c", "k"]
def fit(data):
centroids = {}
for i in range(k):
centroids[i]= data[i]
# That is first k=4 centroids will be the starting k=4 of the dataset
for i in range(tot_iter):
labels = {}
for i in range(k):
labels[i] = []
# feature set in data
for fset in X:
distances = [np.linalg.norm(fset-centroids[centroid]) for centroid in centroids]
# Creating a list of distances where 0th element of the list will be
# the distance to the 0th centroid with data elements.
label = distances.index(min(distances)) # Classification
labels[label].append(fset) # Says that feature set belongs to that centroid
prev_centroids = dict(centroids)
for label in labels:
# pass
centroids[label] = np.average(labels[label], axis=0)
# Taking avergae of all the labels we have and assigning the centroid with that label
# Finds the centroid for previous centroids labels
# Finds the mean of all the features for any given class and redefines the centroid
converged = True
for clabel in centroids:
original_centroid = prev_centroids[clabel]
current_centroid = centroids[clabel]
# Checking for the threshold theta by which the centroid should take movements
if np.sum((current_centroid - original_centroid)/original_centroid * 100) > theta:
converged = False
if converged:
break
for centroid in centroids:
plt.scatter(centroids[centroid][0], centroids[centroid][1], marker="o", color="k", s=150, linewidths=5)
for label in labels:
color = colors[label]
for fset in labels[label]:
plt.scatter(fset[0], fset[1], marker="x", color=color, s=150, linewidths=5)
"""# NEW CENTROIDS"""
fit(X)
"""Note that some points which are classified green previouslt, are now classified according to the nearest centroid
Lets try with smaller and larger cluster for values k=2 and k=6
# K=2
"""
k=2
theta = 0.01
tot_iter = 80
colors = 10*["g", "r", "b", "c", "k"]
def fit(data):
centroids = {}
for i in range(k):
centroids[i]= data[i]
# That is first k=4 centroids will be the starting k=4 of the dataset
for i in range(tot_iter):
labels = {}
for i in range(k):
labels[i] = []
# feature set in data
for fset in X:
distances = [np.linalg.norm(fset-centroids[centroid]) for centroid in centroids]
# Creating a list of distances where 0th element of the list will be
# the distance to the 0th centroid with data elements.
label = distances.index(min(distances)) # Classification
labels[label].append(fset) # Says that feature set belongs to that centroid
prev_centroids = dict(centroids)
for label in labels:
pass
# centroids[label] = np.average(labels[label], axis=0)
# Taking avergae of all the labels we have and assigning the centroid with that label
# Finds the centroid for previous centroids labels
# Finds the mean of all the features for any given class and redefines the centroid
converged = True
for clabel in centroids:
original_centroid = prev_centroids[clabel]
current_centroid = centroids[clabel]
# Checking for the threshold theta by which the centroid should take movements
if np.sum((current_centroid - original_centroid)/original_centroid * 100) > theta:
converged = False
if converged:
break
for centroid in centroids:
plt.scatter(centroids[centroid][0], centroids[centroid][1], marker="o", color="k", s=150, linewidths=5)
for label in labels:
color = colors[label]
for fset in labels[label]:
plt.scatter(fset[0], fset[1], marker="x", color=color, s=150, linewidths=5)
def predict(data):
distances = [np.linalg.norm(data-centroids[centroid]) for centroid in centroids]
label = distances.index(min(distance))
return label
"""# K=2 plot"""
fit(X)
"""# K=6"""
k=6
theta = 0.01
tot_iter = 80
colors = 10*["g", "r", "b", "c", "k", "m"]
def fit(data):
centroids = {}
for i in range(k):
centroids[i]= data[i]
# That is first k=4 centroids will be the starting k=4 of the dataset
for i in range(tot_iter):
labels = {}
for i in range(k):
labels[i] = []
# feature set in data
for fset in X:
distances = [np.linalg.norm(fset-centroids[centroid]) for centroid in centroids]
# Creating a list of distances where 0th element of the list will be
# the distance to the 0th centroid with data elements.
label = distances.index(min(distances)) # Classification
labels[label].append(fset) # Says that feature set belongs to that centroid
prev_centroids = dict(centroids)
for label in labels:
pass
# centroids[label] = np.average(labels[label], axis=0)
# Taking avergae of all the labels we have and assigning the centroid with that label
# Finds the centroid for previous centroids labels
# Finds the mean of all the features for any given class and redefines the centroid
converged = True
for clabel in centroids:
original_centroid = prev_centroids[clabel]
current_centroid = centroids[clabel]
# Checking for the threshold theta by which the centroid should take movements
if np.sum((current_centroid - original_centroid)/original_centroid * 100) > theta:
converged = False
if converged:
break
for centroid in centroids:
plt.scatter(centroids[centroid][0], centroids[centroid][1], marker="o", color="k", s=150, linewidths=5)
for label in labels:
color = colors[label]
for fset in labels[label]:
plt.scatter(fset[0], fset[1], marker="x", color=color, s=150, linewidths=5)
def predict(data):
distances = [np.linalg.norm(data-centroids[centroid]) for centroid in centroids]
label = distances.index(min(distance))
return label
"""# K=6 Plot"""
fit(X)
"""Note that for K=6 it is wrose than k=4
# K-Means : A Try with MNIST dataset
"""
# Import the MNIST dataset
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print('Training Data: {}'.format(x_train.shape))
print('Training Labels: {}'.format(y_train.shape))
print('Testing Data: {}'.format(x_test.shape))
print('Testing Labels: {}'.format(y_test.shape))
fig, axs = plt.subplots(3, 3, figsize = (12, 12))
plt.gray()
for i, ax in enumerate(axs.flat):
ax.matshow(x_train[i])
ax.axis('off')
ax.set_title('Number {}'.format(y_train[i]))
fig.show()
# convert each image to 1 dimensional array
X = x_train.reshape(len(x_train),-1)
Y = y_train
# normalize the data to 0 - 1 One hot
X = X.astype(float) / 255.
print(X.shape)
print(X[0].shape)
"""# Getting Failed when trying to run method fit(X) which is defined in earlier sections
The Error is expected to come since it is very large computation
"""
k=10
theta = 0.01
tot_iter = 80
colors = 10*["g", "r", "b", "c", "k", "m", "y", "w"]
def fit(data):
centroids = {}
for i in range(k):
centroids[i]= data[i]
# That is first k=4 centroids will be the starting k=4 of the dataset
for i in range(tot_iter):
labels = {}
for i in range(k):
labels[i] = []
# feature set in data
for fset in X:
distances = [np.linalg.norm(fset-centroids[centroid]) for centroid in centroids]
# Creating a list of distances where 0th element of the list will be
# the distance to the 0th centroid with data elements.
label = distances.index(min(distances)) # Classification
labels[label].append(fset) # Says that feature set belongs to that centroid
prev_centroids = dict(centroids)
for label in labels:
# pass
centroids[label] = np.average(labels[label], axis=0)
# Taking avergae of all the labels we have and assigning the centroid with that label
# Finds the centroid for previous centroids labels
# Finds the mean of all the features for any given class and redefines the centroid
converged = True
for clabel in centroids:
original_centroid = prev_centroids[clabel]
current_centroid = centroids[clabel]
# Checking for the threshold theta by which the centroid should take movements
if np.sum((current_centroid - original_centroid)/original_centroid * 100) > theta:
converged = False
if converged:
break
for centroid in centroids:
plt.scatter(centroids[centroid][0], centroids[centroid][1], marker="o", color="k", s=150, linewidths=5)
for label in labels:
color = colors[label]
for fset in labels[label]:
plt.scatter(fset[0], fset[1], marker="x", color=color, s=150, linewidths=5)
fit(X)
"""# Use MiniBatchKmeans
*Due to the size of the MNIST dataset, we will use the mini-batch implementation of k-means clustering provided by scikit-learn. This will dramatically reduce the amount of time it takes to fit the algorithm to the data.* Ref: https://medium.com/datadriveninvestor/k-means-clustering-for-imagery-analysis-56c9976f16b6
"""
from sklearn.cluster import MiniBatchKMeans
n_digits = len(np.unique(y_test))
print(n_digits)
# Initialize KMeans model
kmeans = MiniBatchKMeans(n_clusters = n_digits)
# Fit the model to the training data
kmeans.fit(X)
kmeans.labels_
def infer_cluster_labels(kmeans, actual_labels):
inferred_labels = {}
for i in range(kmeans.n_clusters):
# find index of points in cluster
labels = []
index = np.where(kmeans.labels_ == i)
# append actual labels for each point in cluster
labels.append(actual_labels[index])
# determine most common label
if len(labels[0]) == 1:
counts = np.bincount(labels[0])
else:
counts = np.bincount(np.squeeze(labels))
# assign the cluster to a value in the inferred_labels dictionary
if np.argmax(counts) in inferred_labels:
# append the new number to the existing array at this slot
inferred_labels[np.argmax(counts)].append(i)
else:
# create a new array in this slot
inferred_labels[np.argmax(counts)] = [i]
#print(labels)
#print('Cluster: {}, label: {}'.format(i, np.argmax(counts)))
return inferred_labels
def infer_data_labels(X_labels, cluster_labels):
# empty array of len(X)
predicted_labels = np.zeros(len(X_labels)).astype(np.uint8)
for i, cluster in enumerate(X_labels):
for key, value in cluster_labels.items():
if cluster in value:
predicted_labels[i] = key
return predicted_labels
cluster_labels = infer_cluster_labels(kmeans, Y)
X_clusters = kmeans.predict(X)
predicted_labels = infer_data_labels(X_clusters, cluster_labels)
print (predicted_labels[:20])
print (Y[:20])
kmeans = MiniBatchKMeans(n_clusters = 36)
kmeans.fit(X)
# record centroid values
centroids = kmeans.cluster_centers_
# reshape centroids into images
images = centroids.reshape(36, 28, 28)
images *= 255
images = images.astype(np.uint8)
# determine cluster labels
cluster_labels = infer_cluster_labels(kmeans, Y)
# create figure with subplots using matplotlib.pyplot
fig, axs = plt.subplots(6, 6, figsize = (20, 20))
plt.gray()
# loop through subplots and add centroid images
for i, ax in enumerate(axs.flat):
# determine inferred label using cluster_labels dictionary
for key, value in cluster_labels.items():
if i in value:
ax.set_title('Inferred Label: {}'.format(key))
# add image to subplot
ax.matshow(images[i])
ax.axis('off')
# display the figure
fig.show()
"""# PCA"""
# Again load mnist, standardize
from keras.datasets import mnist
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print('Training Data: {}'.format(x_train.shape))
print('Training Labels: {}'.format(y_train.shape))
plt.imshow(x_train[2])
print(y_train[2])
X = x_train.reshape(len(x_train),-1)
Y = y_train
# normalize the data to 0 - 1 One hot
X = X.astype(float) / 255.
print(X.shape)
print(X[0].shape)
print(Y.shape)
new_labels = Y[0:15000]
new_data = X[0:15000]
print('the shape of sample data: '+ str(new_data.shape))
covar_matrix = np.matmul(new_data.T, new_data)
print(covar_matrix.shape)
# From scipy.linearalgebra we can have pre built libs of eigen value and eigen vectors
from scipy.linalg import eigh
# Higest eigen values and vectors
# eigh returns values in ascending order
values, vectors = eigh(covar_matrix, eigvals=(782,783))
vectors = vectors.T
print(vectors.shape)
final_coordinates = np.matmul(vectors,new_data.T)
print(final_coordinates.shape)
# (2X784) X (784X15000)
new_labels.shape
# Adding labels
final_coordinates = np.vstack((final_coordinates, new_labels)).T
df = pd.DataFrame(data=final_coordinates, columns=("PC1","PC2", "label"))
print(df.head())
import seaborn as sb
sb.FacetGrid(df, hue="label", size=6).map(plt.scatter, 'PC1', 'PC2').add_legend()
plt.show()
"""Note that labels 0 (dark blue) and 1 (orange) are completely separated. Moreover, we have just transformed our 784D dataset in 2D plane. Great!"""
# Now using PCA / Prebuilt function
from sklearn import decomposition
pca = decomposition.PCA()
pca.n_components = 2
pca_data = pca.fit_transform(new_data)
print(pca_data.shape)
# Putting to vertical stack
pca_data = np.vstack((pca_data.T, new_labels)).T
pca_dataframe = pd.DataFrame(data=pca_data, columns=("PC1","PC2", "label"))
sb.FacetGrid(pca_dataframe, hue="label", size=6).map(plt.scatter, 'PC1', 'PC2').add_legend()
plt.show()