aboutsummaryrefslogtreecommitdiff
path: root/Assignment 4/ex41.py
diff options
context:
space:
mode:
authorCamil Staps2015-11-27 00:18:32 +0100
committerCamil Staps2015-11-27 00:18:32 +0100
commitd88d00232cfdbfd508834911af6ad89a217b84e1 (patch)
tree20308e5e89f76ce8f987598e26f75db6ad4cbd4e /Assignment 4/ex41.py
parentAssignment 3 report (diff)
Start assignment 4
Diffstat (limited to 'Assignment 4/ex41.py')
-rw-r--r--Assignment 4/ex41.py92
1 files changed, 92 insertions, 0 deletions
diff --git a/Assignment 4/ex41.py b/Assignment 4/ex41.py
new file mode 100644
index 0000000..5ae66db
--- /dev/null
+++ b/Assignment 4/ex41.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Oct 23 14:45:21 2015
+
+@author: Camil Staps, s4498062
+
+This is Python 2 code.
+"""
+
+import sys
+sys.path.insert(0, './packages')
+
+import numpy as np
+from scipy import io as sciio
+from sklearn import cluster
+from clusterPlot import clusterPlot
+from clusterVal import clusterVal
+import matplotlib.pyplot as plt
+
+# 4.1.1
+n = 1
+synth = sciio.loadmat('./data/synth' + str(n) + '.mat')
+X = synth['X']
+y = synth['y']
+centroid, label, inertia = cluster.k_means(X, 4)
+clusterPlot(X, label, centroid, y)
+
+# 4.1.2
+entropies, purities, rands, jaccards = [], [], [], []
+for i in range(1, 11):
+ _, label, _ = cluster.k_means(X, i)
+ entropy, purity, rand, jaccard = clusterVal(y, label)
+ entropies.append(entropy)
+ purities.append(purity)
+ rands.append(rand)
+ jaccards.append(jaccard)
+
+print(entropies, purities, rands, jaccards)
+
+x = np.arange(1,11)
+plt.figure(figsize=(8,8))
+plt.subplot(2,2,1)
+plt.plot(x, entropies, label='Entropy')
+plt.legend()
+plt.subplot(2,2,2)
+plt.plot(x, purities, label='Purity')
+plt.legend(loc=4)
+plt.subplot(2,2,3)
+plt.plot(x, rands, label='Rand')
+plt.legend(loc=4)
+plt.subplot(2,2,4)
+plt.plot(x, jaccards, label='Jaccard')
+plt.legend(loc=4)
+plt.show()
+
+# 4.1.3
+faces = sciio.loadmat('./data/wildfaces.mat')
+X = faces['X']
+k = 0
+centroid, label, inertia = cluster.k_means(X, 10)
+
+n = 10
+plt.figure(figsize=(n*2,4))
+for k in range(0,n):
+ plt.subplot(2, n, k + 1)
+ plt.imshow(np.reshape(X[k,:], (3,40,40)).T)
+ plt.axis('off')
+ plt.subplot(2, n, k + 1 + n)
+ plt.imshow(np.reshape(centroid[label[k],:], (3,40,40)).T)
+ plt.axis('off')
+plt.show()
+
+# 4.1.4
+digits = sciio.loadmat('./data/digits.mat')
+X = digits['X']
+k = 20
+
+plt.figure(figsize=(6,4))
+for k in range(0,24):
+ plt.subplot(4, 6, k + 1)
+ plt.imshow(np.reshape(X[k], (16,16)), cmap=plt.cm.binary)
+ plt.axis('off')
+plt.show()
+
+centroid, label, inertia = cluster.k_means(X, k)
+
+plt.figure(figsize=(6,4))
+for k in range(0,24):
+ plt.subplot(4, 6, k + 1)
+ plt.imshow(np.reshape(centroid[label[k]], (16,16)), cmap=plt.cm.binary)
+ plt.axis('off')
+plt.show()