【问题标题】:Refactoring K-means algorithm in python, using numpy使用 numpy 在 python 中重构 K-means 算法
【发布时间】:2019-09-10 15:01:19
【问题描述】:

我正在研究 python 中的 K-means 算法,并以直观的方式完成了这段代码,并希望提出优化和重构它的建议。

for i in range(N):
        for j in range(K):
               averages[i, j] = np.linalg.norm(trips[i] - centroids[j])**2

        for i in range(N):
                assigns[i] = int(np.argmin(averages[i]))

        for i in range(K):

                temp = np.zeros([F])
                temp = np.expand_dims(temp, axis=0)

                for j in range(N):
                        if(int(assigns[j]) == i):
                                temp = np.insert(temp, 0, trips[j], axis=0);

                temp = temp[:-1, :]

                if(temp.shape[0] > 0):
                        centroids[i] = temp.sum(axis=0) / temp.shape[0]

谢谢!

【问题讨论】:

    标签: python numpy machine-learning refactoring k-means


    【解决方案1】:

    你可以使用列表推导,它应该会加快一点:

    for i1 in range(N):
            averages[i1] = [np.linalg.norm(trips[i1] - centroids[j])**2 for j in range(K)]
    
            assigns = [int(np.argmin(averages[i2])) for i2 in range(N)]
    
            for i3 in range(K):
                    temp = np.zeros([F])
                    temp = np.expand_dims(temp, axis=0)
    
                    for j in range(N):
                            if(int(assigns[j]) == i3):
                                    temp = np.insert(temp, 0, trips[j], axis=0)
    
                    temp = temp[:-1, :]
    
                    if(temp.shape[0] > 0):
                            centroids[i3] = temp.sum(axis=0) / temp.shape[0]
    

    我重命名了一些索引,所以我不知道我是否在公式中选择了正确的索引。无论如何,我不建议在嵌套循环中使用相同的索引,它会产生难以发现的问题。

    【讨论】:

      猜你喜欢
      • 2010-12-05
      • 2018-10-11
      • 2011-09-15
      • 2013-07-03
      • 2017-04-20
      • 2013-04-22
      • 2015-08-16
      相关资源
      最近更新 更多