You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用t-SNE可视化Python3中K-means的多维聚类与质心数据?

Got it, let's walk through a complete, teachable implementation for visualizing your multi-dimensional K-means clusters and centroids using t-SNE in Python 3. I'll include full code with detailed explanations, so you can walk through each step with your students easily.

Complete Implementation Code
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# ----------------------
# Step 1: Prepare your data (adjust this section to match your actual dataset)
# ----------------------
# Your provided centroids (reshape to [n_centroids, n_features] – update the second reshape value to match your feature count)
centroids_list = [0.0, 0.0, 1.125, 0.5, 0.25, 0.375, 0.125, 0.0, 
                  0.75, 0.0, 0.0, 0.0, 0.0, 1.5, 0.5, 0.125, 
                  0.0, 0.75, 0.25, 0.0, 1.75, 0.0, 0.0, 1.125, 
                  0.125, 0.625, 0.25, 0.0, 0.25, 0.0, 0.625, 0.75, 0.0]
# Assuming each centroid has 4 features (32 total values / 8 centroids = 4 features) – adjust this to match your data's dimension
centroids = np.array(centroids_list).reshape(8, 4)

# Generate sample clustered data around centroids (replace this with your actual dataset if you have it)
np.random.seed(42)  # For reproducibility (great for teaching)
X = []
labels = []
for cluster_idx, centroid in enumerate(centroids):
    # Generate 50 samples per centroid with small noise
    samples = np.random.normal(loc=centroid, scale=0.1, size=(50, centroids.shape[1]))
    X.append(samples)
    labels.extend([cluster_idx]*50)

X = np.vstack(X)
labels = np.array(labels)

# If you already have pre-clustered data and labels, skip the above and load your data here:
# X = np.load("your_multi_dimensional_data.npy")
# labels = np.load("your_cluster_labels.npy")
# centroids = np.load("your_centroids.npy")

# ----------------------
# Step 2: Apply t-SNE to reduce dimensions to 2D
# ----------------------
# Initialize t-SNE – adjust perplexity based on your dataset size (typical range: 5-50)
tsne = TSNE(n_components=2, perplexity=30, random_state=42, n_iter=1000)
# Fit and transform the high-dimensional data to 2D
X_tsne = tsne.fit_transform(X)
# Transform centroids to 2D space too (important for visualization)
centroids_tsne = tsne.fit_transform(centroids)

# ----------------------
# Step 3: Visualize the clusters and centroids
# ----------------------
plt.figure(figsize=(10, 8))

# Plot clustered samples
scatter = plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=labels, cmap='viridis', alpha=0.6, label='Cluster Samples')

# Plot centroids with a distinct marker (star) and larger size
plt.scatter(centroids_tsne[:, 0], centroids_tsne[:, 1], c='red', marker='*', s=200, edgecolor='black', label='Centroids')

# Add labels, title, and legend
plt.title('t-SNE Visualization of K-means Clusters and Centroids (2D Projection)', fontsize=14)
plt.xlabel('t-SNE Component 1', fontsize=12)
plt.ylabel('t-SNE Component 2', fontsize=12)
plt.legend()
plt.colorbar(scatter, label='Cluster Label')
plt.grid(True, alpha=0.3)

plt.show()
Step-by-Step Explanation

1. Import Required Libraries

  • numpy: Handles numerical operations and array manipulation (critical for working with high-dimensional data).
  • sklearn.manifold.TSNE: Implements the t-SNE dimensionality reduction algorithm, which excels at preserving local cluster structure when projecting high-dimensional data to 2D/3D.
  • matplotlib.pyplot: Creates the visualization plot.
  • sklearn.cluster.KMeans: Included in case you need to run K-means clustering from scratch (skip this if you already have pre-computed labels/centroids).

2. Data Preparation

  • Centroid Reshaping: Your centroid list is converted to a numpy array and reshaped to [n_centroids, n_features]. I assumed 4 features per centroid (since your list has 32 values, that gives 8 centroids) – make sure to update the reshape value to match your actual data's feature count.
  • Sample Data Generation: For teaching purposes, I generated synthetic data around each centroid with small noise. If you have real clustered data, replace this section with your own data loading code (e.g., np.load() or pandas read_csv()).

3. t-SNE Dimensionality Reduction

  • t-SNE Initialization: We set n_components=2 to get a 2D projection. The perplexity parameter controls how the algorithm balances local vs. global structure (start with 30 for most datasets, adjust based on sample size). random_state ensures reproducibility, which is key for teaching.
  • Transform Data: We apply fit_transform() to both the clustered samples and centroids, so everything is projected into the same 2D space.

4. Visualization

  • Sample Plotting: Clustered samples are plotted with colors corresponding to their cluster labels, using a colormap for clarity.
  • Centroid Highlighting: Centroids are marked with red stars (distinct from samples) to make them easy to identify – this helps students see how clusters are centered around these points.
  • Labels & Legend: We add descriptive titles, axis labels, and a legend to make the plot self-explanatory for your students.

内容的提问来源于stack exchange,提问作者intelligent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:35:15