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

如何用Python导入CSV文件并执行TSNE后可视化结果

完整可运行代码及常见问题修正

核心实现代码

import pandas as pd
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt

# 1. 读取CSV数据
df = pd.read_csv("你的数据文件路径.csv")

# 分离分组标签与主成分特征
labels = df.iloc[:, 0]  # 提取第一列的分组标签
features = df.iloc[:, 1:]  # 提取从第二列开始的主成分数据

# 2. 执行t-SNE降维
# 可根据数据量调整perplexity(建议5-50)、迭代次数n_iter等参数
tsne = TSNE(n_components=2, perplexity=30, random_state=42, n_iter=1000)
tsne_results = tsne.fit_transform(features)

# 3. 按分组着色绘制可视化图
plt.figure(figsize=(10, 8))
# 为每个唯一分组分配专属颜色
unique_labels = labels.unique()
color_map = plt.cm.get_cmap('tab10', len(unique_labels))

for idx, label in enumerate(unique_labels):
    # 筛选当前分组对应的所有数据点
    mask = labels == label
    plt.scatter(tsne_results[mask, 0], tsne_results[mask, 1],
                color=color_map(idx), label=str(label), alpha=0.7)

plt.title("t-SNE降维可视化结果")
plt.xlabel("t-SNE Component 1")
plt.ylabel("t-SNE Component 2")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

常见问题修正点

  • 数据读取异常:如果CSV无表头,需添加header=None参数,手动指定列名:df.columns = ["label"] + [f"PC{i}" for i in range(1, 51)]
  • 降维效果差:若结果点聚合混乱,可调高perplexity(样本量越大值可越高,数千行建议20-50),或增加n_iter至2000以上
  • 内存占用过高:若主成分列数过多,可先通过PCA预降维减少计算压力:
    from sklearn.decomposition import PCA
    pca = PCA(n_components=10)  # 先将特征降到10维
    reduced_features = pca.fit_transform(features)
    tsne_results = tsne.fit_transform(reduced_features)
    
  • 着色失效:若分组标签是数值型分类,无需额外转换,直接使用即可;若为字符串标签,unique()方法可自动识别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:57:02