create a app with following descriptions: 3D Data Clustering Visualizer Description: Visualize clustering algorithms (like k-means) on 3D data using interactive Plotly 3D scatter plots. Features: Allow users to set the number of clusters, see cluster centroids, and color-code points based on cluster assignment.
To upload files, please first save the app
import streamlit as st
import numpy as np
import pandas as pd
import plotly.express as px
st.title("3D Data Clustering Visualizer")
# Sidebar for user input
st.sidebar.header("User Input Parameters")
n_clusters = st.sidebar.slider("Number of clusters", 1, 10, 3)
# Generate random 3D data
np.random.seed(42)
X = np.random.rand(100, 3) * 100
# K-means clustering
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
clusters = kmeans.fit_predict(X)
centroids = kmeans.cluster_centers_
# Create a DataFrame
clusters_df = pd.DataFrame(X, columns=["X", "Y", "Z"])
clusters_df['Cluster'] = clusters
centroids_df = pd.DataFrame(centroids, columns=["X", "Y", "Z"])
centroids_df['Cluster'] = range(n_clusters)
# Create the 3D scatter plot
fig = px.scatter_3d(clusters_df, x='X', y='Y', z='Z', color='Cluster', title='3D Clustering Visualization',
labels={'X': 'X Axis', 'Y': 'Y Axis', 'Z': 'Z Axis'}, hover_name=clusters_df.index)
# Adding centroids to the plot
fig.add_trace(px.scatter_3d(centroids_df, x='X', y='Y', z='Z', color='Cluster',
color_discrete_sequence=['black'], marker=dict(size=10, symbol='x')).data[0])
st.plotly_chart(fig)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?