使用python自编程实现聚类k-means算法并画出图像
好的,下面是使用Python自编程实现聚类k-means算法并画出图像的步骤:
1. 导入必要的库
```python
import numpy as np
import matplotlib.pyplot as plt
```
2. 生成数据
我们先生成一些随机数据,用于演示聚类算法。
```python
np.random.seed(0)
X = np.vstack((np.random.randn(100, 2) * 0.75 + np.array([1, 0]),
np.random.randn(100, 2) * 0.25 + np.array([-0.5, 0.5]),
np.random.randn(100, 2) * 0.5 + np.array([-0.5, -0.5])))
```
这里生成了三个簇,每个簇包含100个点。
3. 实现k-means算法
```python
def k_means(X, k, max_iter=100):
# 随机初始化k个中心点
centers = X[np.random.choice(len(X), k, replace=False)]
for i in range(max_iter):
# 计算每个点到中心点的距离
distances = np.linalg.norm(X[:, np.newaxis] - centers, axis=2)
# 找到距离最近的中心点
labels = np.argmin(distances, axis=1)
# 更新中心点
for j in range(k):
centers[j] = np.mean(X[labels == j], axis=0)
return labels, centers
```
这里的k是指簇的个数,max_iter是指最大迭代次数。
4. 调用k-means算法并画出图像
```python
labels, centers = k_means(X, 3)
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.scatter(centers[:, 0], centers[:, 1], marker='*', s=200, c='#050505')
plt.show()
```
这里先调用k_means函数得到每个点所属的簇和簇的中心点,然后用散点图将数据点和中心点画出来。
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
X = np.vstack((np.random.randn(100, 2) * 0.75 + np.array([1, 0]),
np.random.randn(100, 2) * 0.25 + np.array([-0.5, 0.5]),
np.random.randn(100, 2) * 0.5 + np.array([-0.5, -0.5])))
def k_means(X, k, max_iter=100):
# 随机初始化k个中心点
centers = X[np.random.choice(len(X), k, replace=False)]
for i in range(max_iter):
# 计算每个点到中心点的距离
distances = np.linalg.norm(X[:, np.newaxis] - centers, axis=2)
# 找到距离最近的中心点
labels = np.argmin(distances, axis=1)
# 更新中心点
for j in range(k):
centers[j] = np.mean(X[labels == j], axis=0)
return labels, centers
labels, centers = k_means(X, 3)
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.scatter(centers[:, 0], centers[:, 1], marker='*', s=200, c='#050505')
plt.show()
```
运行代码后,会得到一个散点图,其中不同颜色的点表示不同的簇,星号表示簇的中心点。
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。