我在地图上有特定的点,我需要将它们分组到具有相同大小的不同簇,最后一个簇可以是count %n
。我读了这些答案1、2、和3,但没有帮助。我尝试过不同的方法,但没有一种有效。在这段代码中,我指定了n_clusters=4
,因为这是一个集群的最佳数量,我可以对它们进行排序,并从排序的点获取n
个最佳点,然后我将遍历所有点。例如,我需要图中所示的32
点是集群到4
集群,并且每个集群都有8
点
dfcluster = DataFrame(position, columns=['x', 'y'])
kmeans = KMeans(n_clusters=4).fit(dfcluster)
centroids = kmeans.cluster_centers_
# plt.scatter(dfcluster['x'], dfcluster['y'], c=kmeans.labels_.astype(float), s=50, alpha=0.5)
# plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
# plt.show()
dfcluster['cluster'] = kmeans.labels_
dfcluster=dfcluster.drop_duplicates(['x', 'y'], keep='last')
dfcluster = dfcluster.sort_values(['cluster', 'x', 'y'], ascending=True)
# d=pd.DataFrame()
# m = pd.DataFrame()
# n=8
# for x in range(4) :
# m= dfcluster[dfcluster.cluster == x]
#
#
# if len(m) > int( n /2)-1:
# m=m.head(int(n/2)-1)
# # for idx, row in m.iterrows():
# # print("code3 group", "=", row['cluster'])
# d=d.append(m,ignore_index = True)
#
# else :
# d=d.append(m,ignore_index = True)
#
#
# if len(d)>=n:
# dfcluster = d
# dfcluster.groupby('cluster').nth(n))
dfcluster=dfcluster.head(n)
i=0
if (len(dfcluster )< n):
change_df()
我发现这个模块使用了Same Size Constrained K-Means Heuristics: Use Heuristics methods to reach the same size clustering,它给出了相同大小的组
我从
pip install size-constrained-clustering
或pip install git+https://github.com/jingw2/size_constrained_clustering.git
开始,您可以使用minmax flow
或Heuristics
如果
size-constrained-clustering
模块有问题,可以使用这些类,但需要安装k-means-constrained
SameSizeKMeansMinCostFlow
类base
类集群本身将决定每个集群需要多少数据点
如果要根据接近程度将数据分成4个同样大的组,则应确定距离最远的4个点,然后迭代地向这些数据点添加最近的邻居,以防这些数据点不在群集中。 但我不希望这看起来很漂亮
相关问题 更多 >
编程相关推荐