【问题标题】:Python Clustering numerical dataPython聚类数值数据
【发布时间】:2016-01-29 20:49:32
【问题描述】:

我正在关注一个教程,其中“kmeans”算法是整个示例的主要部分。 “行”列表作为要聚类的数据传递。 Pearson 函数提供第二个参数,一个关系系数,k=3 是聚类的数量。从 kmeans 函数返回的“最佳匹配”是一个分组/聚集索引值列表,对应于属于每个集群的行中的元素。因为我需要制作散点图,所以我需要它们的值。如何返回值而不是索引?

rows=[(1,1),(3,6),(11,2),(7,19),(22,11),(32,11)]

def pearson(v1,v2):

#sums
sum1=sum(v1)
sum2=sum(v2)
print(sum1)
#sums of the sqs
sum1Sq=sum([pow(v,2) for v in v1])
sum2Sq=sum([pow(v,2) for v in v2])

#sum of products
pSum=sum([v1[i]*v2[i] for i in range(len(v1))])

#calculate pearson R
num=pSum-(sum1*sum2/len(v1))
den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1)))
if den==0: return 0

return 1.0-num/den 



def kmeans(rows,distance=pearson,k=3):
#Determine the min and max values for each point

#COunt through "rows"(data) and find min and max values
ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows]))

for i in range(len(rows[0]))]    
#create k randomly placed centroids within len of 'data'
clusters=[[random.random()*(ranges[i][1]-ranges[i][0])+ranges[i][0]

for i in range(len(rows[0]))] for j in range(k)]
lastmatches=None
for t in range(100):
    print 'Iteration %d' % t

    bestmatches=[[] for i in range(k)]

    #find which centroid is the closest to each row
    for j in range(len(rows)):
        row=rows[j]
        bestmatch=0
        for i in range(k):
            d=distance(clusters[i],row)
            if d<distance(clusters[bestmatch],row): bestmatch=i

        bestmatches[bestmatch].append(j)

    if bestmatches==lastmatches: break
    lastmatches=bestmatches

    #move centroids to the avg of members
    for i in range(k):
        avgs=[0.0]*len(rows[0])
        if len(bestmatches[i])>0:
            #print(len(bestmatches[i]))
            for rowid in bestmatches[i]:
                for m in range(len(rows[rowid])):
                    avgs[m]+=rows[rowid][m]
                for j in range(len(avgs)):
                    avgs[j]/=len(bestmatches[i])
                clusters[i]=avgs

    return bestmatches

【问题讨论】:

  • 本教程来自 Toby Segaran 的“Programming Collective Intelligence”。在“发现组”一章中,他介绍了一些数据挖掘概念并提供了此代码。
  • 据报道该书有许多代码错误...oreilly.com/catalog/errataunconfirmed.csp?isbn=9780596529321 尽管您似乎缺少基本的 Python 经验...

标签: python algorithm cluster-analysis


【解决方案1】:

不要使用具有 pearson 相关性的 k-means

这可能会失败,因为 pearson 相关和 mean 不兼容,可能会阻止算法收敛。更糟糕的是,它可能会产生无效值。

如果你取两个向量

1 2 3 4 5
9 8 7 6 5

那么平均值是

5 5 5 5 5

而得到的 mean 不能与 Pearson corrleation 一起使用,因为它是常数值。

K-means 仅适用于 Brgeman 散度,例如平方欧几里得。因为它是关于方差最小化,而不是距离最小化

K-means 不能用于任意距离。如果您有其他距离,请使用 k 中位数 (PAM) 或其他聚类算法。

【讨论】:

  • 谢谢@Anony-Mousse。我正在重写一个距离度量函数来获得欧几里得。我也看到了最佳匹配在哪里被分配了索引值,当它最初被制作成一个列表,然后 j 值被附加到它时。
猜你喜欢
  • 2020-07-08
  • 2016-02-14
  • 2018-09-05
  • 2014-07-14
  • 2022-11-18
  • 2018-05-04
  • 2012-05-24
  • 2022-06-14
  • 2013-04-09
相关资源
最近更新 更多