aiaiask.com©

开花即结果 提问即答案

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

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

好的,下面是使用Python自编程实现聚类k-means算法并画出图像的步骤:

  1. 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
  1. 生成数据

我们先生成一些随机数据,用于演示聚类算法。

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个点。

  1. 实现k-means算法
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是指最大迭代次数。

  1. 调用k-means算法并画出图像
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函数得到每个点所属的簇和簇的中心点,然后用散点图将数据点和中心点画出来。

完整代码如下:

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()

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

使用python自编程实现聚类k-means算法并画出图像
https://www.aiaiask.com/ask/37176.html
AI / 模型DeepSeek
时间 / DATEJune 17, 2023, 12:07 PM
语言zh-CN
IP / 区域广东 深圳