python - 从头开始Python中的K表示

标签 python numpy machine-learning k-means

我有一个 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)

最佳答案

(扩展答案,稍后格式化) 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), :] 意味着我们沿第一个轴选择一个元素,并沿第二个轴选取共享第一个索引的每个元素。实际上,我们正在选择矩阵的随机行。

(注释很好地解释了这段代码,我建议您阅读 numpy 索引列表理解以进一步说明)。

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 中的行数相同。稍后将填充该向量。我们正在初始化该数组以便稍后填充。

错误= dist(C, C_old, None)。求两个矩阵之间的距离。我相信这个函数可以在脚本的其他地方定义。

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

while...当条件成立时执行此 block 。

对于 [0...(X 中的行数 - 1)] 中的 i:

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

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

对于每个(0..平均值 - 1):

如果 cluster[j] == i],则点 = [X[j][:-1],对于范围 (len(X)) 内的 j。这是列表理解。创建 X 的行列表,其中包含除最后一项之外的所有行,但仅包含属于第 j 个簇的行。

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

C[i][:] = numpy.zeros(C[i].shape)。创建一个由零组成的向量,稍后填充,并使用该向量作为簇矩阵 C 的第 i 行。

其他:

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

关于python - 从头开始Python中的K表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845820/

相关文章:

python - 在 python 中排序字典列表

python - Kivy:如何检索在 python 中创建的复选框(或其他小部件)的 ID 或事件状态

python - Django Rest Framework 中的空路由

python - 同时分配给一个numpy数组

numpy - 仅在两个数组都非零的情况下将一个 numpy 数组除以另一个

python - Heroku无法在requirements.txt中识别NumPy

machine-learning - 如何计算在 TensorFlow 中运行模型所需的 GPU 内存?

python - 将变量传递给框架

android-studio - java.lang.IllegalArgumentException : No OpKernel was registered to support Op 'GatherV2' with these attrs.

python - 如何使用数据库训练智能聊天机器人,然后添加到 iOS 应用程序