Tristan Lassiter
Tristan Lassiter

Reputation: 43

TSNE - 3D graph

Imagine data ncoll and wcoll as 4000ish random numbers.

I want to run them through TSNE, then create a 3-dimensional plot.

If I plot this I end up with essentially a 2D graph, so something is going wrong, but I'm not entirely sure what.

Ultimately I want to plot the first half in red and the second in blue on the same 3D graph.

print(__doc__)

from time import time

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import NullFormatter

from sklearn import manifold
from sklearn.utils import check_random_state

c = 1000
 # Open File
ncoll_fn = "C:/Users/xxlassi/Downloads/trajectory_demo/trajectory_270252769939974_run__uid_-1808183947_tag_collision_0.0.txt"
wcoll_fn = "C:/Users/xxlassi/Downloads/trajectory_demo/trajectory_271551342150600_run__uid_-918721219_tag_collision_0.01.txt"

ncoll = []
wcoll = []

with open( ncoll_fn ) as f:
    ncoll = [ np.array([ float(el) for el in line.strip().split(',') ]) for line in f.readlines() ]
    ncoll = np.array( ncoll )

with open( wcoll_fn ) as f:
    wcoll = [ np.array([ float(el) for el in line.strip().split(',') ]) for line in f.readlines() ]
    wcoll = np.array( wcoll )

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

arr = np.concatenate((wcoll, ncoll), axis=0)
mid = int(len(arr)/2)
print (mid)

tsne = manifold.TSNE(n_components=3, init='pca',random_state=0, perplexity= 30, n_iter=5000)
trans_data = tsne.fit_transform(arr)

ax.scatter(arr[:,0][0:mid], arr[:,1][0:mid], c= 'r')
ax.scatter(arr[:,0][mid:], arr[:,1][mid:], c= 'b')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.title("t-SNE")
plt.axis('tight')
plt.show()

Upvotes: 1

Views: 12110

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23099

You need to plot trans_data with 3d scatter instead to plot the t-SNE-transformed data:

trans_data = tsne.fit_transform(arr)

ax.scatter(trans_data[:,0][0:mid], trans_data[:,1][0:mid], trans_data[:,2][0:mid], c= 'r', s = 100, marker='+')
ax.scatter(trans_data[:,0][mid:], trans_data[:,1][mid:], trans_data[:,2][mid:], c= 'b', s = 100, marker='.')

enter image description here

Upvotes: 1

Related Questions