k-means算法、层次聚类算法、DBSCAN算法和谱聚类算法,代码案例
时间: 2024-01-30 22:04:23 浏览: 148
K-means,FCM,谱聚类,DBSCAN,AP,DPC聚类算法matlab源代码.zip
以下是Python中对四种聚类算法的代码实现和案例:
1. k-means算法
```python
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# 生成数据
x1 = np.random.normal(0.5, 0.2, (100, 2))
x2 = np.random.normal(2.5, 0.2, (100, 2))
x3 = np.random.normal(1.5, 0.2, (100, 2))
X = np.vstack((x1, x2, x3))
# 训练模型
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(X)
# 可视化结果
labels = kmeans.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)
plt.show()
```
2. 层次聚类算法
```python
import numpy as np
from sklearn.cluster import AgglomerativeClustering
import matplotlib.pyplot as plt
# 生成数据
x1 = np.random.normal(0.5, 0.2, (100, 2))
x2 = np.random.normal(2.5, 0.2, (100, 2))
x3 = np.random.normal(1.5, 0.2, (100, 2))
X = np.vstack((x1, x2, x3))
# 训练模型
agg = AgglomerativeClustering(n_clusters=3)
agg.fit(X)
# 可视化结果
labels = agg.labels_
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')
plt.show()
```
3. DBSCAN算法
```python
import numpy as np
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
# 生成数据
x1 = np.random.normal(0.5, 0.2, (100, 2))
x2 = np.random.normal(2.5, 0.2, (100, 2))
x3 = np.random.normal(1.5, 0.2, (100, 2))
X = np.vstack((x1, x2, x3))
# 训练模型
dbscan = DBSCAN(eps=0.3, min_samples=5)
dbscan.fit(X)
# 可视化结果
labels = dbscan.labels_
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')
plt.show()
```
4. 谱聚类算法
```python
import numpy as np
from sklearn.cluster import SpectralClustering
import matplotlib.pyplot as plt
# 生成数据
x1 = np.random.normal(0.5, 0.2, (100, 2))
x2 = np.random.normal(2.5, 0.2, (100, 2))
x3 = np.random.normal(1.5, 0.2, (100, 2))
X = np.vstack((x1, x2, x3))
# 训练模型
spectral = SpectralClustering(n_clusters=3)
spectral.fit(X)
# 可视化结果
labels = spectral.labels_
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')
plt.show()
```
阅读全文