【问题标题】:How to export the output (cluster labels) of k-means algorithm with the ids in the original data如何使用原始数据中的 id 导出 k-means 算法的输出(集群标签)
【发布时间】:2019-09-09 11:24:18
【问题描述】:

我有一个总结网络的数据,包括用户的 cookie id、会话 id、材料数量和网络中的跳转次数。我想对它们进行聚类并进一步分析它们。因此,需要知道哪个会话中的哪个cookie id 标记在哪个集群中。示例数据:

cookie_id|ses_num|num_material|num_jump
2345         1        2           1 
2345         2        8           12
3456         1        3           2 

我已使用最后两列应用了 k-means 聚类,但无法将聚类输出返回到正确的 id,因为我无法使用 cookie id 和会话 id 作为聚类的输入。

columns = defaultdict(list) 
with open('num_jumps_materials_in_network.csv',"r") as file: 
    reader = csv.reader(file, delimiter='|', quotechar='"')
    next(reader)
    for row in reader: 
        for i, v in enumerate(row): 
           columns[i].append(v) 

cookie_id = columns[0]
ses_num = columns[1]
num_mat = columns[2]
num_jump = columns[3]

x1 = []
x2 = []

i = 0
while (i<len(num_mat)):
    a = int(num_mat[i])
    b = int(num_jump[i])
    x1.append(a)
    x2.append(b)
    i+=1

X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)

# 6 according to elbow method
kmeans = KMeans(n_clusters=6)
kmeans.fit(X)
y_kmeans = kmeans.predict(X)


fig, (ax1, ax2) = pyplot.subplots(2, figsize=(15,15))
fig.suptitle('Clustering users by k-means (k=6)')
# whole 
ax1.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=30, cmap='gist_rainbow')
# closer look 
ax2.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=30, cmap='gist_rainbow')
ax2.set_xlim([0, 500])
ax2.set_ylim([0, 500])

pyplot.savefig('k_means_clusters_demo.png')

我想输出如下结果:

cookie_id|ses_num|num_material|num_jump|cluster
2345         1        2           1        0
2345         2        8           12       2
3456         1        3           2        1

非常感谢, A.

【问题讨论】:

    标签: python export-to-csv k-means


    【解决方案1】:

    我在想数组的顺序必须像在 array.sort() 中一样重新排序,但显然它没有。以下对我有用。

    clusters = kmeans.labels_
    i=0 
    while(i < len(clusters)):
        print(cookie_id[I],clusters[i])
        i+=1 
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2015-05-03
      • 2020-12-05
      • 2016-08-21
      • 2018-10-04
      • 2016-03-13
      • 2022-01-01
      • 2018-11-05
      • 2019-02-03
      相关资源
      最近更新 更多