stzhao's picture
Update app.py
444d5c7 verified
import numpy as np
import gradio as gr
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import base64
from io import BytesIO
# Function to create a tensor from input vectors and plot them
def plot_vectors(file):
try:
# Load the numpy array from the uploaded file
tensor = np.load(file.name)
# Check if the tensor is 2D
if len(tensor.shape) != 2:
raise ValueError("The file must contain a 2D array of 1D vectors.")
# Apply t-SNE for dimensionality reduction
tsne = TSNE(n_components=2, random_state=42)
reduced_vectors = tsne.fit_transform(tensor)
# Extract x and y components from the reduced vectors
x = reduced_vectors[:, 0]
y = reduced_vectors[:, 1]
# Create the plot
plt.figure(figsize=(8, 8))
plt.scatter(x, y, c='blue', marker='o', label='Vectors')
plt.xlabel('X component')
plt.ylabel('Y component')
plt.title('2D Distribution of Vectors (t-SNE)')
plt.legend()
plt.grid(True)
plt.axis('equal') # Equal scaling on both axes
# Save the plot to a buffer
buf = BytesIO()
plt.savefig("result.png")
buf.seek(0)
plt.close()
# Convert the buffer to a base64-encoded string
buf.seek(0)
img_str = base64.b64encode(buf.getvalue()).decode('utf-8')
# Return the base64-encoded image string
return "result.png"
except Exception as e:
return str(e)
# Create a Gradio interface
iface = gr.Interface(
fn=plot_vectors,
inputs=gr.File(label="Upload a .npy file containing a 2D array of 1D vectors"),
outputs=gr.Image(type="filepath", label="Visualization Result"),
examples=[["random_array.npy"]] # Example file
)
# Launch the interface
iface.launch()