Last active
December 26, 2020 18:52
-
-
Save daa233/695439f33a41970f6da9ca6f3b15d27d to your computer and use it in GitHub Desktop.
T-SNE visualization by `sklearn.manifold.TSNE`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from sklearn.manifold import TSNE | |
from matplotlib import pyplot as plt | |
def draw_tsne(X, y, save_fig=None, show=False): | |
""" | |
T-SNE visualization by `sklearn.manifold.TSNE`. | |
Reference: https://www.scipy-lectures.org/packages/scikit-learn/auto_examples/plot_tsne.html | |
:param X: data to be projected | |
:param y: data labels | |
:param save_fig: the path to save the fig | |
:return: None | |
""" | |
assert len(X) == len(y) | |
t_sne = TSNE(n_components=2, random_state=0, verbose=1) | |
X_2d = t_sne.fit_transform(X) | |
num_ids = len(np.unique(y)) | |
target_ids = range(num_ids) | |
plt.figure(figsize=(6, 5)) | |
# distinct color map, https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib | |
cmap = plt.cm.get_cmap('hsv', num_ids+1) | |
for i in target_ids: | |
plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=cmap(i), s=2, label=str(i)) | |
plt.legend() | |
if save_fig: | |
plt.savefig(save_fig) | |
if show: | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment