首页 > ChatAI > AI文库 >

使用python自编程实现聚类k-means算法并画出图像

分享 55674

分享

好的,下面是使用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()
```

运行代码后,会得到一个散点图,其中不同颜色的点表示不同的簇,星号表示簇的中心点。

相关推荐

新征程上,青年如何握紧接力棒,走好奋斗路为主题写一篇思想报告

AI文库

神秘岛高三读后感700字

高三

韩国请回答1988电视剧观后感

电视剧观后感

九年级数学二次根式知识点

别名数学

语文教学工作计划模板

工作计划范文

热门图文

上一篇:劳育与德育和美育之间有何关系1000字论文

下一篇:劳育与德育和美育之间有何关系