Py学习  »  Python

K在Python中是指从头开始

Jerry M. • 4 年前 • 802 次点击  

我有一个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)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48446
 
802 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Ethan Henderson
Reply   •   1 楼
Ethan Henderson    5 年前

(扩展答案,稍后格式化) x是数据,作为矩阵。 使用[]符号,我们从矩阵中提取切片或选择单个元素。您可能想检查NUMPY数组索引。 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html choice从数据矩阵的第一维的大小中随机选择k个元素,不需要替换。 注意,在索引中,使用[]语法,我们看到我们有两个条目。numpy.random.choice和“:”。 “”表示我们沿着这条轴线。

因此,x[NoPy.Adv.Orth.(X.St[ 0 ],k,替换= false),]意味着我们沿着第一个轴选择一个元素,并沿着第二个共享第一个索引的每一个元素。有效地,我们选择一个矩阵的随机行。

(这些评论很好地解释了这段代码,我建议你读一下NUMPY索引列表理解,以便进一步说明)。

C[C[j][:-1]表示范围内的j(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中的行数相同。稍后将填充此向量。我们正在初始化此数组以便稍后填充。

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

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

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

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

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

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

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

如果簇[j]=i,则范围(len(X))内j的点=[X[j][:-1]这是一个列表理解。创建一个x行的列表,除了最后一个条目之外,都包含在其中,但是如果该行属于jth集群,则只包含该行。

如果没有点。如果没有东西属于一个集群。

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

其他:

C[i]=NP.Mean(点,轴=0)。将簇矩阵的第i行c指定为簇中的平均点。我们遍历行(轴=0)。这是我们更新集群。