#find the central sample
min_dis=np.array([1000,1000,1000,1000,1000])
min_X=np.array([-1,-1,-1,-1,-1])
for i in range(len(y_pred)):
if y_pred[i]==0:
curr_dis=np.sqrt(np.sum(np.square(X_arr[i]-centroids[0])))
if curr_dis<min_dis[0]:
min_dis[0]=curr_dis
min_X[0]=i
elif y_pred[i]==1:
curr_dis=np.sqrt(np.sum(np.square(X_arr[i]-centroids[1])))
if curr_dis<min_dis[1]:
min_dis[1]=curr_dis
min_X[1]=i
elif y_pred[i]==2:
curr_dis=np.sqrt(np.sum(np.square(X_arr[i]-centroids[2])))
if curr_dis<min_dis[2]:
min_dis[2]=curr_dis
min_X[2]=i
elif y_pred[i]==3:
curr_dis=np.sqrt(np.sum(np.square(X_arr[i]-centroids[3])))
if curr_dis<min_dis[3]:
min_dis[3]=curr_dis
min_X[3]=i
else:
curr_dis=np.sqrt(np.sum(np.square(X_arr[i]-centroids[4])))
if curr_dis<min_dis[4]:
min_dis[4]=curr_dis
min_X[4]=i
print(min_X)
N=5
#find the central sample
central_pat=[]
for n in range(N):
cluster=[]
origin_index=[]
for i in range(len(y_pred)):
if y_pred[i]==n:
cluster.append(X_arr[i])
origin_index.append(i)
min_dis=1000
min_index=-1
for j in range(len(cluster)):
curr_dis=np.sqrt(np.sum(np.square(cluster[j]-centroids[n])))
if curr_dis<min_dis:
min_dis=curr_dis
min_index=j
central_pat.append(origin_index[min_index])
print("central pattern:")
print(central_pat)
for n in range(N):
print(central_pat[n])
print(pat_name[central_pat[n]])
两种思路确实都是正确的,但是在第一种思路中,因为min_dis初始化的值是1000,所以系统设定其数据类型为int,下面判断curr_dis<min_dis时,会将curr_dis赋值给min_dis,所以会进行强制类型转换,第一个curr_dis=0.66,赋值后min_dis=0,不可能再出现比这个小的距离了,所以就一直是第一个样本。
但是没搞清楚为什么第二种方法不会出这种问题。。。