给定一个NxM特征向量作为numpy矩阵。是否有任何可以使用L1距离(曼哈顿距离)的Kmeans算法对其进行聚类的例程?蟒蛇中L1距离的kmeans
2
A
回答
2
我不认为这是SciPy的提供明确的,但你应该看看下面的例子:
2
有代码 is-it-possible-to-specify-your-own-distance-function-using-scikits-learn-k-means下, 它使用任何20奇指标在scipy.spatial.distance中。 另请参阅 L1-or-L.5-metrics-for-clustering;你能否用L1与L2评论你的结果?
3
这是一个使用L1距离(曼哈顿距离)的Kmeans算法。为了通用性,特征向量被表示为列表,该列表很容易转换为numpy矩阵。
import random
#Manhattan Distance
def L1(v1,v2):
if(len(v1)!=len(v2):
print “error”
return -1
return sum([abs(v1[i]-v2[i]) for i in range(len(v1))])
# kmeans with L1 distance.
# rows refers to the NxM feature vectors
def kcluster(rows,distance=L1,k=4):# Cited from Programming Collective Intelligence
# Determine the minimum and maximum values for each point
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
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 for 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 the results are the same as last time, this is complete
if bestmatches==lastmatches:
break
lastmatches=bestmatches
# Move the centroids to the average of their members
for i in range(k):
avgs=[0.0]*len(rows[0])
if len(bestmatches[i])>0:
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
相关问题
- 1. 汉明距离蟒蛇改进
- 2. 颜色分割使用Kmeans,Opencv蟒蛇
- 3. 我想通过距离蟒蛇质心的距离对数据进行分类
- 4. 寻找蟒蛇中欧式距离的最快方法
- 5. 逃离领先的蟒蛇
- 6. 蟒蛇计算与高度角和原始速度的距离
- 7. 蟒蛇发现多个号码之间的距离在列表
- 8. 通过数组循环找到蟒蛇欧氏距离
- 9. 蟒蛇谷歌地球坐标距离计算
- 10. 把纬度和经度到距离矩阵,在蟒蛇
- 11. 加快地面集合中所有对之间的L1距离
- 12. 如何指定R中kmeans的距离度量?
- 13. 蛇的头部距离身体有几点距离(C++游戏)
- 14. 蟒蛇在蟒蛇
- 15. Matlab:如何实现L1距离计算的矢量化版本
- 16. 分离mutidimensional阵列numpy的蟒蛇
- 17. 蟒蛇matplotlib不均匀间距y
- 18. 使用jaccard距离矩阵的Kmeans聚类
- 19. 如何覆盖Kmeans算法的距离评估方法
- 20. 蟒numpy的成对编辑距离
- 21. 在apache的火花蟒蛇K-均值自定义的距离公式推
- 22. 蟒蛇在PowerShell中VS蟒蛇CLI
- 23. 更新蟒蛇3.5蟒蛇
- 24. 无法在蟒蛇蟒蛇
- 25. 蟒蛇2.7:从CMD蟒蛇
- 26. 蟒蛇CSV是分离太多
- 27. 如何摆脱SimpleDocTemplate()中的间距。蟒蛇。 ReportLab
- 28. 距离Cell塔的距离
- 29. 蟒蛇
- 30. 蟒蛇