Coding-kmeans聚类+T-SEN可视化

摘要

kmeans聚类,T-SEN可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE

# 加载数据
data = np.load('test.npy')

# 假设 data 的特征在第一维
features = data[:, 0, :] # 根据实际数据结构选择特征

# 聚类
num_clusters = 3 # 根据需要设置聚类的数量
kmeans = KMeans(n_clusters=num_clusters, random_state=0)
kmeans.fit(features)
clusters = kmeans.labels_ # 获取每个样本的聚类标签

# 使用 t-SNE 降维
tsne = TSNE(n_components=2, random_state=10)
feature_tsne = tsne.fit_transform(features)

# 绘制 t-SNE 散点图
plt.figure(figsize=(10, 8))
scatter = plt.scatter(feature_tsne[:, 0], feature_tsne[:, 1], c=clusters, cmap='viridis', marker='o')

# 创建颜色条
legend1 = plt.legend(*scatter.legend_elements(), title="Clusters")
plt.gca().add_artist(legend1)

plt.title('t-SNE Visualization of Clusters')
plt.xlabel('t-SNE Component 1')
plt.ylabel('t-SNE Component 2')
plt.grid()
plt.show()