【问题标题】:Python: k-means clusteringPython:k 均值聚类
【发布时间】:2021-09-27 21:20:51
【问题描述】:

我正在尝试对 .csv 文件的经度和纬度数据使用 k-means 聚类,但我不想绘制图形,只想获取并打印质心,以便我可以在谷歌地图上搜索它们。有人知道如何编码吗?

import pandas as pd
import numpy as np
import csv


with open('fileName.csv', 'r') as infile:
  csv_reader = csv.reader (infile,  delimiter=',')
  x = []
  y = []

  for row in csv_reader:
    if row[3] != 'LONGITUDE':
      x.append(float(row[3]))
      y.append(float(row[4]))

    df = pd.DataFrame({
    'x': x,
    'y': y
    })
    #implement x and y in k-means and print the centroids

【问题讨论】:

  • 到目前为止您尝试过什么?请展示你的作品。
  • 我建议查看例如 Scikit Learn k-means 聚类类 scikit-learn.org/stable/modules/generated/… 的文档。当您使用该类执行 k-means 聚类时,它会将聚类中心保存在 cluster_centers_ 属性中。
  • @Taxel 刚刚添加了代码 :)

标签: python machine-learning k-means


【解决方案1】:

我建议查看 Shapely 库。

from shapely.geometry import MultiPoint
import pandas as pd
import numpy as np
import csv

# Easy way to read your csv file in
df = pd.read_csv('fileName.csv').rename(columns={'LONGITUDE': 'x', 'LATITUDE': 'y'})

# Assumes you have a column 'cluster_id' that references the cluster id for each coordinate
cluster_ids = df['cluster_id'].unique()
kmeans_clusters = []
for cluster_id in cluster_ids:

    # Filtered df for each cluster id    
    cluster_df = df.loc[df['cluster_id'] == cluster_id]
    x_values = cluster_df['x'].tolist()
    y_values = cluster_df['y'].tolist()

    xy_pairs = [point for point in zip(x_values, y_values)]
    kmeans_clusters.append(xy_pairs)

# Where kmeans_clusters is a list of your clusters, each containing a list of xy pairs
centroids = []
for cluster in kmeans_clusters:

    if len(cluster) > 1:
        # Create a convex hull, find the centroid
        convex_hull = MultiPoint(cluster).convex_hull
        centroid = convex_hull.centroid
        # Unpack to tuple object
        centroids.append(list(centroid.coords)[0])
    else:
        # Single point cluster, it is the centroid
        centroids.append(cluster[0])

print(centroids)

【讨论】:

  • 我试过了,但它给了我一个错误提示:“ValueError: A LinearRing must have at least 3坐标元组”
  • 我已经用一种更好的方法来查找集群的质心更新了答案,它解释了单点集群:)
  • 代码运行但它仍然给我一个奇怪的输出:(( --> ['x', 'y'] 它没有给我值。我只是添加了我编码的内容到目前为止,我将“kmeans_cluster”替换为“df”,因为这是我的 x 和 y 值存储在我的代码中的位置。也许我做错了什么?
  • 你希望输出是什么样的?
  • 我希望它以 [ x,y ] 的格式为我提供质心的值
猜你喜欢
  • 2014-07-24
  • 2017-02-15
  • 2015-02-09
  • 2017-12-30
  • 1970-01-01
  • 2018-11-28
  • 2017-01-15
  • 2014-07-23
  • 2016-05-20
相关资源
最近更新 更多