Created
March 16, 2025 10:30
-
-
Save monperrus/b73b8c318ff440b7e7596f5da7850c69 to your computer and use it in GitHub Desktop.
t-sne visualization in python, with tooltips on points
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 | |
import plotly.express as px | |
import pandas as pd | |
import glob | |
import json | |
# Sample data - replace with your own dataset | |
# data = np.random.rand(100, 20) # 100 samples, 20 features | |
matrix = [] | |
labels = [] | |
for i in glob.glob("cache/embedding.specter_v2/*json"): | |
data = json.load(open(i)) | |
if not data or not 'embedding' in data or not data['embedding'] or not data['embedding']['vector']: | |
continue | |
matrix.append(data['embedding']['vector']) | |
labels.append(data['title']) | |
# create panda from matri | |
data = np.array(matrix) | |
# labels = # Sample labels | |
# Perform t-SNE | |
tsne = TSNE(n_components=2, random_state=42) | |
tsne_results = tsne.fit_transform(data) | |
# Create a DataFrame for plotting | |
df = pd.DataFrame({ | |
'x': tsne_results[:, 0], | |
'y': tsne_results[:, 1], | |
'label': labels, | |
}) | |
# Create interactive plot with tooltips | |
fig = px.scatter( | |
df, x='x', y='y', | |
hover_data=['label'], | |
title='t-SNE Visualization' | |
) | |
fig.update_traces(marker=dict(size=10)) | |
fig.update_layout( | |
hoverlabel=dict( | |
bgcolor="white", | |
font_size=12 | |
) | |
) | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment