# 聚类数据 import numpy as np pos = np.arange(0, 6, 5) # 两个中心点在x=0,x=5 size = 50 # 生成两个簇 x = np.array([ np.random.normal(i+np.random.random(), 1, size) for i in pos ]).flatten() y = np.array([ np.random.normal(i+np.random.random(), 1, size) for i in pos ]).flatten() print(x.shape, y.shape)编写Python程序,实现以下要求: 画出上面数据的散点图 采用scipy.cluster.vq.kmeans()聚类,并在散点图中画出聚类中心点
时间: 2024-01-10 19:04:55 浏览: 29
以下是实现要求的Python代码:
```python
import numpy as np
from scipy.cluster.vq import kmeans
import matplotlib.pyplot as plt
pos = np.arange(0, 6, 5) # 两个中心点在x=0,x=5
size = 50 # 生成两个簇
x = np.array([np.random.normal(i+np.random.random(), 1, size) for i in pos]).flatten()
y = np.array([np.random.normal(i+np.random.random(), 1, size) for i in pos]).flatten()
# 画出散点图
plt.scatter(x, y)
# 聚类
data = np.array(list(zip(x, y)))
centroids, _ = kmeans(data, 2)
# 画出聚类中心点
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=200, linewidths=3, color='r')
plt.show()
```
运行程序后,会弹出一个散点图窗口,其中红色叉号表示聚类中心点。
相关问题
from sklearn.cluster import KMeans import numpy as np kmeans = KMeans(n_clusters=5, random_state=0).fit(X) kmeans.labels_ kmeans.predict(X) kmeans.cluster_centers_代码含义
这段代码使用了 scikit-learn 中的 KMeans 聚类算法,对数据集 X 进行聚类,将其分为 5 个簇。具体含义如下:
- `from sklearn.cluster import KMeans`:从 scikit-learn 中导入 KMeans 类。
- `import numpy as np`:导入 NumPy 库,用于处理数组和矩阵。
- `kmeans = KMeans(n_clusters=5, random_state=0).fit(X)`:创建 KMeans 对象,设置聚类数目为 5,随机种子为 0,然后使用 `fit()` 方法拟合数据集 X。
- `kmeans.labels_`:获取每个样本的簇标签。
- `kmeans.predict(X)`:对测试数据集 X 进行预测,返回测试数据集中每个样本的簇标签。
- `kmeans.cluster_centers_`:获取每个簇的中心点。
如何将该图改为折现簇状图import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans# 生成随机数据 X = np.random.rand(100, 2)# 设置聚类的数量为3 kmeans = KMeans(n_clusters=3, random_state=0).fit(X)# 统计每个类别的数量 labels, counts = np.unique(kmeans.labels_, return_counts=True)# 绘制簇状图 plt.plot(labels, counts, align='center') plt.xticks(labels, ['Cluster {}'.format(i) for i in range(len(labels))]) plt.ylabel('Number of samples') plt.title('KMeans Clustering') plt.show()
将该图改为折线簇状图,需要将 `plt.plot()` 函数替换为 `plt.bar()` 函数,并且加上 `plt.plot()` 函数绘制折线图。
以下是改为折线簇状图的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# 生成随机数据
X = np.random.rand(100, 2)
# 设置聚类的数量为3
kmeans = KMeans(n_clusters=3, random_state=0).fit(X)
# 统计每个类别的数量
labels, counts = np.unique(kmeans.labels_, return_counts=True)
# 绘制簇状图
plt.bar(labels, counts, align='center', alpha=0.5)
plt.xticks(labels, ['Cluster {}'.format(i) for i in range(len(labels))])
plt.ylabel('Number of samples')
plt.title('KMeans Clustering')
# 绘制折线图
plt.plot(labels, counts, 'r')
plt.show()
```
运行以上代码可以得到一个折线簇状图,横坐标为类别名称,纵坐标为每个类别的数量。其中,红色的折线表示每个类别的数量。