Skip to content

Instantly share code, notes, and snippets.

@izikeros
Created February 20, 2023 13:31
Show Gist options
  • Save izikeros/f050ee203561b0189d73e2aaa3e6579e to your computer and use it in GitHub Desktop.
Save izikeros/f050ee203561b0189d73e2aaa3e6579e to your computer and use it in GitHub Desktop.
T-SNE demo (2D, 3D)
import numpy as np
from sklearn.manifold import TSNE
from plotly import graph_objs as go
# generate 10-dimensional data
X = np.random.rand(100, 10)
print(X.shape)
# reduce to 3 components
X_embedded = TSNE(n_components=3).fit_transform(X)
print(X_embedded.shape)
# indices for classes
indices = (list(range(50)), list(range(50,100)),)
class_1_indices, class_2_indices = indices
# prepare plot for class "1"
trace1 = go.Scatter3d(
x=X_embedded[class_1_indices, 0],
y=X_embedded[class_1_indices, 1],
z=X_embedded[class_1_indices, 2],
mode='markers',
marker=dict(color='rgb(0,127,0)', size=3, opacity=0.5),
)
# prepare plot for class "2"
trace2 = go.Scatter3d(
x=X_embedded[class_2_indices, 0],
y=X_embedded[class_2_indices, 1],
z=X_embedded[class_2_indices, 2],
mode='markers',
marker=dict(color='rgb(127,0,0)', size=3, opacity=0.5),
)
# finalize plot
layout = dict(height=600, width=600)
data = [trace1, trace2]
fig = go.Figure(data=data, layout=layout)
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment