我正在为一个班级做作业,即:
给定一组N个测量值(r1,r2,...,rN),我们将首先将奇数编号的测量值分配给1类,将偶数编号的测量值分配给2类。然后重复以下两个步骤:
•更新步骤:计算每个群集内测量值的平均值(平均值)。 •分配步骤:将每个度量分配给具有最接近平均值的群集。
如果出现平局,请将测量值分配给群集1。 重复上述步骤,直到群集分配不更改。在聚类分配稳定之前,无法预先确定需要多少步骤。
我原来用来解决这个问题的代码却是不成功的:
import numpy as np
def clusterAnalysis(reflectance):
oldCluster=np.zeros(np.size(reflectance))
Cluster=(np.arange(0,np.size(reflectance))%2)+1
while np.all(oldCluster!=Cluster):
oldCluster=np.copy(Cluster)
m1=np.mean(reflectance[Cluster==1])
m2=np.mean(reflectance[Cluster==2])
for i in range(np.size(reflectance)):
d1= abs(reflectance[i]-m1)
d2= abs(reflectance[i]-m2)
if d1<=d2:
Cluster[i]=1
else:
Cluster[i]=2
return Cluster
这没用。但是,当我更换
while np.all(oldCluster!=Cluster):
使用:
while not np.all(oldCluster==Cluster):
它确实有效!
任何人都能解释为什么会这样吗?
答案 0 :(得分:2)
它不一样。这样:
while np.all(oldCluster!=Cluster):
应为:
while not np.any(oldCluster==Cluster):
更多信息: