AI 534 HW5: Unsupervised Learning (15 pts)¶

This HW is about unsupervised learning (clustering and dimensionality reduction):

  1. $k$-means clustering implementation
  2. $k$-means clustering for image segmentation
  3. dimensionality reduction: PCA and t-SNE

We will use the "Old Faithful", MNIST, and Fashion-MNIST datasets for these tasks.

Part 1: $k$-Means Clustering (7.5 pts)¶

  1. Implement your own $k$-means function kmeans(data, k) using numpy. data is a numpy array and k is the number of clusters. (1.5 pts)
    • The initial centroids should be random choices of data points (make sure there are duplicate centroids by np.random.choice() with replace=False).
    • Your function should return the final centroids and labels (i.e., the centroid index for each data point).
    • Note that you should as few for-loops as possible.
  2. Try your method on the "old-faithful" dataset (see below). (2 pts)
    • For each iteration, plot one figure including:
      • the two centroids, and
      • the two sets of points in two different colors, each belonging to one cluster, like the one from the textbook/slides).
    • Are the final results the same as the one from the Bishop textbook and slides? If not, why?
  3. Try your method on all MNIST images of label 1, with k=3. (1 pt)
    • Plot the centroids as images, with title being the number of images in this cluster.
    • What do you observe? Do the results make sense?
    • Also do each class (0-9).
  4. Compare your result with sklearn.cluster.KMeans below (which I did for you for class 1, but you need to do the rest). Do your resutls match sklearn results? (1 pt)
  5. Now use your $k$-means on the first 10,000 images of MNIST with k=10. (2 pts)
    • Plot each centroids as an image.
    • For each plot, include in the title:
      • (a) the size of this cluster,
      • (b) the majority label, and
      • (c) its percentage within the corresponding cluster,
      • e.g., cluster 1 might have 1,035 images where 65% are labeled 9.
    • What do you observe? Do they make sense?
In [183]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import fetch_openml
import seaborn as sns
In [184]:
geyser = sns.load_dataset("geyser")  # Columns: duration, waiting, kind
oldfaithful = geyser[["duration", "waiting"]].to_numpy()
In [185]:
plt.scatter(oldfaithful[:, 0], oldfaithful[:, 1])
Out[185]:
<matplotlib.collections.PathCollection at 0x312620cd0>
No description has been provided for this image
In [175]:
X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False, parser='auto')
y = y.astype(np.int64) # convert labels from str to int
plt.imshow(np.mean(X[y==1], axis=0).reshape(28, 28)) # average 0
Out[175]:
<matplotlib.image.AxesImage at 0x3217d87d0>
No description has been provided for this image
In [86]:
kmeans = KMeans(n_clusters=3)
kmeans.fit(X[y==1]) # run kmeans (k=2) on images with label 0
Out[86]:
KMeans(n_clusters=3)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
n_clusters  3
init  'k-means++'
n_init  'auto'
max_iter  300
tol  0.0001
verbose  0
random_state  None
copy_x  True
algorithm  'lloyd'
In [88]:
fig, axes = plt.subplots(1, 3, figsize=(5, 5)) # 1 row, 2 columns
for i in range(3):
    axes[i].set_title(f"{np.sum(kmeans.labels_ == i)}") # size of cluster
    axes[i].imshow(kmeans.cluster_centers_[i].reshape(28, 28))    
No description has been provided for this image

Part 2: $k$-means for Image Segmentation (3 pts)¶

A very interesting application of $k$-means is image segmentation by color. Here you are trying to cluster the pixels based purely on their colors, without considering their locations. Here is a classical example from the Bishop textbook (2007):

image

As you can see, you would divide the pixels into $k$ groups based on color similiarities (Euclidean distance in RGB space), and represent each group by its centroid. You can use your own code or sklearn, but again, use as few for loops as possible.

Try it on one of your own photos (e.g., yourself, your pet, your backyard, your office, etc.).

Part 3: PCA and t-SNE (4.5 pts)¶

You don't need to implement PCA (because we didn't teach SVD). Instead, just use sklearn.

We will use the fashion-mnist data for this part; the ten classes (0-9) and some examples are listed below:

img

  1. I demonstrated below how to do PCA using sklearn on the first 500 images of label 3 (dress), where I projected the 784 dimensional space to 2D. Does the result make sense? What are the two principal components representing? (0.5 pts)
  2. Repeat the above question for all other classes. (1 pt)
  3. At the end of the notebook, I demonstrated how to do PCA on the first 500 images across all labels, i.e., the real first 500 images of the whole dataset, using different colors for different labels, and using transparency b/c there are a lot overlapping. What are the two PCs representing? (0.5 pts)
  4. In the above result, do the different classes overlap in this 2D projection? (0.5 pts)
  5. Redo the above using t-SNE, a (more advanced) non-linear dimensionality reduction method by Hinton (Turing Laureate and Nobel Laureate). What differences can you observe between t-SNE and PCA? What is the main reason behind these differences? (1 pt)
  6. Redo this comparison between PCA and t-SNE on MNIST digits instead of Fashion MNIST. What differences do you observe between the two datasets? (1 pt)
In [114]:
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from sklearn.decomposition import PCA

mnist = fetch_openml("fashion-mnist", version=1, as_frame=False, parser="auto")
XX = mnist.data / 255.0
yy = mnist.target.astype(int)
In [155]:
def draw_PCA(data, labels, method, imagebox_func):
    pca = method(n_components=2) # 784 -> 2 dimensions 
    coords = pca.fit_transform(data) # [500, 2]

    fig, ax = plt.subplots(figsize=(14, 10))
    
    # set axes limits
    ax.set_xlim(coords[:, 0].min() - .3, coords[:, 0].max() + .3)
    ax.set_ylim(coords[:, 1].min() - .3, coords[:, 1].max() + .3)
    
    for img, y, coord in zip(data, labels, coords):
        img = img.reshape(28, 28)
        ab = AnnotationBbox(
            imagebox_func(img, y),
            coord,                # the 2D (x, y) coordinates of this image in the PCA projection
            frameon=False,
            pad=0,
        )
        ax.add_artist(ab)
    
    ax.set_xlabel(f"PC 1")
    ax.set_ylabel(f"PC 2")
    ax.set_title("2D PCA Projection")
    plt.show()
In [157]:
X_class = XX[yy==3][:500] # [500, 784]
y_class = yy[yy==3][:500]

draw_PCA(X_class, y_class, PCA, lambda img, _: OffsetImage(1.0 - img, zoom=0.7, cmap="gray")) # reverse img (black<->white) for white background
No description has been provided for this image
In [182]:
def transparent_box(img, y):
    r, g, b, _ = plt.get_cmap("tab10")(y)
    rgba = np.zeros((28, 28, 4), dtype=np.float32)
    rgba[..., 0] = r
    rgba[..., 1] = g
    rgba[..., 2] = b
    rgba[..., 3] = img  # Transparent background (0), opaque strokes (1)

    return OffsetImage(rgba, zoom=0.45)

draw_PCA(XX[:500], yy[:500], PCA, transparent_box) # unique transparent color for each class
No description has been provided for this image