【问题标题】:K Means in Python from Scratch从零开始的 Python 中的 K 均值
【发布时间】:2019-07-17 15:41:30
【问题描述】:

我有一个用于 k-means 算法的 python 代码。 我很难理解它的作用。 像C = X[numpy.random.choice(X.shape[0], k, replace=False), :] 这样的行让我很困惑。

有人能解释一下这段代码实际上在做什么吗? 谢谢

def k_means(data, k, num_of_features):
    # Make a matrix out of the data
    X = data.as_matrix()
    # Get k random points from the data
    C =  X[numpy.random.choice(X.shape[0], k, replace=False), :]
    # Remove the last col
    C = [C[j][:-1] for j in range(len(C))]
    # Turn it into a numpy array
    C = numpy.asarray(C)
    # To store the value of centroids when it updates
    C_old = numpy.zeros(C.shape)
    # Make an array that will assign clusters to each point
    clusters = numpy.zeros(len(X))
    # Error func. - Distance between new centroids and old centroids
    error = dist(C, C_old, None)
    # Loop will run till the error becomes zero of 5 tries
    tries = 0
    while error != 0 and tries < 1:
        # Assigning each value to its closest cluster
        for i in range(len(X)):
            # Get closest cluster in terms of distance
            clusters[i] = dist1(X[i][:-1], C)
        # Storing the old centroid values
        C_old = deepcopy(C)
        # Finding the new centroids by taking the average value
        for i in range(k):
            # Get all of the points that match the cluster you are on
            points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]
            # If there were no points assigned to cluster, put at origin
            if not points:
                C[i][:] = numpy.zeros(C[i].shape)
            else:
                # Get the average of all the points and put that centroid there
                C[i] = numpy.mean(points, axis=0)
        # Erro is the distance between where the centroids use to be and where they are now
        error = dist(C, C_old, None)
        # Increase tries
        tries += 1
    return sil_coefficient(X,clusters,k)

【问题讨论】:

  • 您是在问 k-means 的一般工作原理,还是只是这个函数?
  • 这个功能特别。我想我对实际算法本身有很好的理解,但我们应该从这个例子开始,这让我很困惑。所有的数据处理对我来说真的很陌生。我正在尝试查看文档,但它没有帮助,所以为了节省我几个小时的时间,我真的祈祷有人可以提供代码的演练解释。
  • 啊。不幸的是,我对 Python 有点生疏。我希望你需要一个通用的 K-means 解释。祝你好运。

标签: python numpy machine-learning k-means


【解决方案1】:

(扩展答案,稍后将格式化) X 是数据,作为矩阵。 使用 [] 表示法,我们从矩阵中获取切片或选择单个元素。您可能想查看 numpy 数组索引。 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html numpy.random.choice 从数据矩阵的第一个维度的大小中随机选择 k 个元素而不进行替换。 请注意,在索引中,使用 [] 语法,我们看到我们有两个条目。 numpy.random.choice 和“:”。 ":" 表示我们正在沿该轴进行所有操作。

因此,X[numpy.random.choice(X.shape[0], k, replace=False), :] 意味着我们沿第一个轴选择一个元素,并沿第二个轴获取共享该第一个索引的每个元素.实际上,我们正在选择矩阵的随机行。

(cmets 很好地解释了这段代码,我建议您阅读 numpy indexing an list comprehensions 以进一步阐明)。

C[C[j][:-1] for j in range(len(c))] "C[" 之后的部分使用列表推导来选择矩阵 C 的部分。

C[j] 表示矩阵 C 的行。 我们使用 [:-1] 来占用但不包括行的最后一个元素。我们对矩阵 C 中的每一行执行此操作。这将删除矩阵的最后一列。

C = numpy.asarray(C)。这会将矩阵转换为 numpy 数组,因此我们可以用它来做一些特殊的 numpy 事情。

C_old = numpy.zeros(C.shape)。这将创建一个稍后填充的零矩阵,其大小与 C 相同。我们正在初始化此数组以供稍后填充。

集群 = numpy.zeros(len(x))。这将创建一个零向量,其维度与矩阵 X 中的行数相同。稍后将填充该向量。我们正在初始化这个数组以便稍后填充。

error = dist(C, C_old, None)。取两个矩阵之间的距离。我相信这个函数会在你的脚本的其他地方定义。

tries = 0。将轮胎计数器设置为 0。

while...在此条件为真时执行此块。

for i in [0...(X 中的行数 - 1)]:

簇[i] = dist1(X[i][:-1], C);把X的第i行最接近哪个簇放在簇的第i个位置。

C_old = deepcopy(C) - 创建一个新的 C 副本。不要只是移动指针。

对于每个(0..number of mean - 1):

points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]。这是一个列表理解。创建 X 的行列表,除了最后一个条目之外的所有行,但仅包含属于第 j 个集群的行。

如果不是积分。如果没有任何东西属于集群。

C[i][:] = numpy.zeros(C[i].shape)。创建一个零向量,稍后填充,并将此向量用作集群矩阵 C 的第 i 行。

其他:

C[i] = np.mean(点,轴=0)。将簇矩阵 C 的第 i 行指定为簇中的平均点。我们对各行求和(轴 = 0)。这是我们更新我们的集群。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多