几天前我开始了一门python课程。我在python分配中遇到了循环问题,即:
给定一组N个测量值(r1,r2,…,rN),我们首先将奇数编号的测量值分配给 等级1,偶数测量值为等级2。然后重复以下两个步骤:
•更新步骤:计算每个集群内测量的平均值(平均值)
•分配步骤:将每个测量值分配给具有最接近平均值的集群。如果打成平局, 将测量值分配给簇1
重复上述步骤,直到集群分配不变。怎么做还不能事先确定 在集群分配稳定之前,需要执行许多步骤
问题定义 创建一个函数,该函数以反射率测量向量作为输入,并返回聚类向量 使用上述算法计算分配
我创建了一个代码:
import numpy as np
import math
def clusterAnalysis(reflectance):
ref=np.size(reflectance)# all N measurements
even=np.any(ref %2==0)# N measurements are even numbers
uneven=np.any(ref%2>0)# N measurements are odd number
mean1=np.mean(even)#average of even numbers in cluster 2
mean2=np.mean(uneven)# average of odd numbers in cluster 1
sub1=abs(ref-mean1)
sub2=abs(ref-mean2)
while sub1<=sub2:
clusterAssigment="1"
else:
clusterAssigment="2"
return clusterAssigments
#print(clusterAnalysis(np.array([1.7, 1.6, 1.3, 1.3, 2.8, 1.4,
#2.8, 2.6, 1.6, 2.7])))
**新代码:
import math
def clusterAnalysis(reflectance):
reflectance=np.arange(reflectance.size)
evens =reflectance % 2 == 0 # N measurements are even numbers
clusters = np.ones(reflectance.shape)
clusters[evens] = 2
while True:
mean_even=np.mean(reflectance[evens])
mean_odd=np.mean(reflectance[np.logical_not(evens)])
diff_even = np.abs(reflectance - mean_even)
diff_odd = np.abs(reflectance - mean_odd)
new_clusters= np.ones(reflectance.shape)
new_clusters[diff_even < diff_odd] = 2
clusterAssigments= new_clusters
if np.all(clusters == new_clusters):
break
clusters = new_clusters
clusterAssigments= new_clusters
return clusterAssigments
print(clusterAnalysis(np.array([1.7, 1.6, 1.3, 1.3, 2.8, 1.4,2.8, 2.6, 1.6, 2.7])))```**
The code above does not work at all. My output should be :`2 2 2 2 1 2 1 1 2 1 `
I have been working on this for last 2 days and I just dont know what I am doing wrong...
你的while循环永远不会结束。您从不修改
sub1
或sub2
,因此while循环只是旋转和旋转,sub1
始终小于sub2
您遇到的问题是,在while循环的每次迭代中,您都需要根据旧集群的平均值计算出新集群,然后检查它们是否已更改
您是对的,您需要一个while循环,您可以使用如下内容:
编辑: 我将试着给你一个拼图的片段
假设我有两个20个介于0和200之间的随机数的列表,我想得到奇数和偶数的平均值:
另一次编辑:
好的,最后一块拼图:)
所以我们想找出
x
中哪一个最接近mean_even
,哪一个最接近mean_odd
。我们可以做一些类似于您最初尝试的事情:您需要更改一些变量名,以使用逻辑索引从clusters数组(而不是evens数组)获取平均值,但这基本上可以满足您的所有需要
请注意,我之前做
mean_odd
时犯了一个错误。我不小心将布尔数组变成了数字,从而破坏了逻辑索引,这就是为什么我将它更新为使用np.logical_not
。如果有兴趣的话,我可以更详细地解释它是如何工作的相关问题 更多 >
编程相关推荐