聚类算法python代码
时间: 2023-07-17 15:11:01 浏览: 174
以下是Python中常见的几种聚类算法的代码示例:
1. K均值聚类算法:
```python
from sklearn.cluster import KMeans
import numpy as np
# 生成数据
X = np.random.rand(100, 2)
# 进行聚类
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
# 获取聚类结果
labels = kmeans.labels_
centers = kmeans.cluster_centers_
```
2. 层次聚类算法:
```python
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
X = np.random.rand(100, 2)
# 进行聚类
Z = linkage(X, 'ward')
# 绘制聚类树
fig, ax = plt.subplots(figsize=(15, 20))
dendrogram(Z, ax=ax)
plt.show()
```
3. 密度聚类算法:
```python
from sklearn.cluster import DBSCAN
import numpy as np
# 生成数据
X = np.random.rand(100, 2)
# 进行聚类
dbscan = DBSCAN(eps=0.3, min_samples=5).fit(X)
# 获取聚类结果
labels = dbscan.labels_
```
4. 均值漂移聚类算法:
```python
from sklearn.cluster import MeanShift
import numpy as np
# 生成数据
X = np.random.rand(100, 2)
# 进行聚类
meanshift = MeanShift().fit(X)
# 获取聚类结果
labels = meanshift.labels_
centers = meanshift.cluster_centers_
```
以上代码仅供参考,具体实现可能因算法不同而有所区别。
阅读全文