This lesson is being piloted (Beta version)

Data visualization with TSNE

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to apply TSNE for data visualization?

Objectives
  • Apply TSNE from scikit-learn package

13. TSNE for Visualization

Load scikit-learn library and create some sample data

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.manifold import TSNE
from sklearn import cluster, datasets, mixture

# ============
# Generate datasets. We choose the size big enough to see the scalability
# of the algorithms, but not too big to avoid too long running times
# ============
n_samples = 500
seed = 30

Noisy Circle data

noisy_circles = datasets.make_circles(
    n_samples=n_samples, factor=0.5, noise=0.05, random_state=seed
)
X,y = noisy_circles
dfX = pd.DataFrame(X,columns=["X1","X2"])
dfX["Cluster"]=y

sns.scatterplot(x="X1", y="X2",
    data=dfX, 
    hue='Cluster', # color by cluster
    legend=True).set(title="Noisy Circle Raw plot")

image

model_tsne = TSNE(n_components=2)
tsne_X = model_tsne.fit_transform(dfX)
df_tsne = pd.DataFrame(tsne_X,columns=['TSNE1','TSNE2'])
df_tsne['Cluster'] = y

sns.scatterplot(x="TSNE1", y="TSNE2",
    data=df_tsne, 
    hue='Cluster', # color by cluster
    legend=True).set(title="TSNE")

image

my_plot

import matplotlib.animation as animation
prange = range(0,100)

def animate(p):
    plt.clf()  # Clear the previous frame
    model_tsne = TSNE(n_components=2,perplexity=p+1)
    tsne_X = model_tsne.fit_transform(dfX)
    df_tsne = pd.DataFrame(tsne_X,columns=['TSNE1','TSNE2'])
    df_tsne['Cluster'] = y
    
    sns.scatterplot(x="TSNE1", y="TSNE2",
        data=df_tsne, 
        hue='Cluster', # color by cluster
        legend=True).set(title="Perplexity = {}".format(p))

ani = animation.FuncAnimation(plt.gcf(), animate, frames=len(prange),interval=10)
ani.save('noisy_moon.gif', writer='pillow') 

noisy_circle_i10

Noisy Moon

noisy_moons = datasets.make_moons(n_samples=n_samples, noise=0.05, random_state=seed)
X,y = noisy_moons

Noisy_moon

noisy_moon

Blobs data with 3 groups

X, y = datasets.make_blobs(n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5],random_state=123)

Blobs

blobs

MNIST data

from tensorflow.keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
for i in range(64):
    ax = plt.subplot(8, 8, i+1)
    ax.axis('off')
    plt.imshow(X_train[i], cmap='Greys')

image

X = X_test.reshape(10000,28*28)
y = y_test
model_tsne = TSNE(n_components=2)
tsne_X = model_tsne.fit_transform(X)
df_tsne = pd.DataFrame(tsne_X,columns=['TSNE1','TSNE2'])
df_tsne['Cluster'] = y
tsne = sns.lmplot(x="TSNE1", y="TSNE2",
  data=df_tsne, 
  fit_reg=False, 
  hue='Cluster', # color by cluster
  legend=True,
  scatter_kws={"s": 5}, # specify the point size
  height=8)

image

MNIST

model_tsne = TSNE(n_components=3)
tsne_X = model_tsne.fit_transform(X)
df_tsne = pd.DataFrame(tsne_X,columns=['TSNE1','TSNE2','TSNE3'])
df_tsne['Cluster'] = y
fig = plt.figure(figsize=(50, 30))
ax = plt.axes(projection ='3d')
# defining all 3 axis
x = df_tsne["TSNE1"]
y = df_tsne["TSNE2"]
z = df_tsne["TSNE3"]

# plotting
ax.scatter(x, y, z, c = df_tsne["Cluster"])
ax.set_title('3D line plot geeks for geeks')
plt.show()

image

from PIL import Image

tx, ty = df_tsne['TSNE1'], df_tsne['TSNE2']
tx = (tx-np.min(tx)) / (np.max(tx) - np.min(tx))
ty = (ty-np.min(ty)) / (np.max(ty) - np.min(ty))

width = 4000
height = 3000
max_dim = 10
full_image = Image.new(mode="RGB", size=(width, height),color = (255, 255, 255))
for idx, x in enumerate(X_test):
    tile = Image.fromarray(np.uint8(x * 255))
    rs = max(1, tile.width / max_dim, tile.height / max_dim)
    full_image.paste(tile, (int((width-max_dim) * tx[idx]),
                            int((height-max_dim) * ty[idx])))
full_image
full_image.save("MNIST_number.jpg")

MNIST_number

FMNIST data

from tensorflow.keras.datasets import fashion_mnist
(X_train,y_train),(X_test,y_test) = fashion_mnist.load_data()
X = X_test.reshape(10000,28*28)
y = y_test
model_tsne = TSNE(n_components=2,perplexity=30)
tsne_X = model_tsne.fit_transform(X)

Cluster_name = ["T-shirt/top","Trouser","Pullover","Dress","Coat",
                "Sandal","Shirt","Sneaker","Bag","Ankle boot"]

df_tsne = pd.DataFrame(tsne_X,columns=['TSNE1','TSNE2'])
df_tsne['Cluster'] = y
df_tsne['Cluster_name'] = pd.Series(y).apply(lambda x:Cluster_name[x])

tsne1 = sns.lmplot(x="TSNE1", y="TSNE2",
  data=df_tsne, 
  fit_reg=False, 
  hue='Cluster_name', # color by cluster
  legend=True,
  scatter_kws={"s": 5}, # specify the point size
  height=8)

image

tx, ty = df_tsne['TSNE1'], df_tsne['TSNE2']
tx = (tx-np.min(tx)) / (np.max(tx) - np.min(tx))
ty = (ty-np.min(ty)) / (np.max(ty) - np.min(ty))

from PIL import Image
width = 4000
height = 3000
max_dim = 10
full_image = Image.new(mode="RGB", size=(width, height),color = (255, 255, 255))


for idx, x in enumerate(X_test):
    tile = Image.fromarray(np.uint8(x * 255))
    rs = max(1, tile.width / max_dim, tile.height / max_dim)
    full_image.paste(tile, (int((width-max_dim) * tx[idx]),
                            int((height-max_dim) * ty[idx])))

full_image.save("FMNIST.jpg")

FMNIST

Dashboard with Python Shiny:

Dashboard

Key Points

  • Visualization