import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.cluster import KMeans from scipy.spatial import Voronoi, voronoi_plot_2d # 生成示例数据 data = df.iloc[:,1:15] # 标准化处理 scaler = StandardScaler() data_scaled = scaler.fit_transform(data) # 主成分分析 pca = PCA(n_components=5) data_pca = pca.fit_transform(data_scaled) # 聚类分析 kmeans = KMeans(n_clusters=3) kmeans.fit(data_pca) labels = kmeans.labels_ centers = kmeans.cluster_centers_ # 绘制Voronoi图 vor = Voronoi(centers) voronoi_plot_2d(vor) # 绘制样本点 plt.scatter(data_pca[:, 0], data_pca[:, 1], c=labels) # 设置坐标轴标签和标题 plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Voronoi Diagram') # 显示图形 plt.show()
时间: 2024-04-08 22:30:45 浏览: 120
import numpy as np(2).py
您的代码看起来几乎是正确的,但有一点需要注意。Voronoi图是在原始数据空间中绘制的,而不是在主成分空间中。因此,在绘制Voronoi图之前,我们需要将主成分投影回原始数据空间。以下是修改后的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.spatial import Voronoi, voronoi_plot_2d
# 生成示例数据
data = df.iloc[:, 1:15]
# 标准化处理
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)
# 主成分分析
pca = PCA(n_components=5)
data_pca = pca.fit_transform(data_scaled)
# 聚类分析
kmeans = KMeans(n_clusters=3)
kmeans.fit(data_pca)
labels = kmeans.labels_
centers = kmeans.cluster_centers_
# 将主成分投影回原始数据空间
data_projected = pca.inverse_transform(data_pca)
# 绘制Voronoi图
vor = Voronoi(centers)
voronoi_plot_2d(vor)
# 绘制样本点
plt.scatter(data_projected[:, 0], data_projected[:, 1], c=labels)
# 设置坐标轴标签和标题
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Voronoi Diagram')
# 显示图形
plt.show()
```
请确保在代码中替换`df.iloc[:, 1:15]`为您实际的数据。这段代码将绘制投影回原始数据空间后的样本点,并在Voronoi图上显示聚类结果。
阅读全文