问题
I have a data summarising a network including users' cookie id, session id, number of materials, and number of jumps in the network. I would like to cluster them and further analyse them. So, need to know which cookie id in which session is labelled in which cluster. Example data:
cookie_id|ses_num|num_material|num_jump
2345 1 2 1
2345 2 8 12
3456 1 3 2
I have applied k-means clustering using the last two columns but cannot return the clustering output to the right id as I cannot use cookie id and session id as input for clustering.
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')
I would like to output the result as below:
cookie_id|ses_num|num_material|num_jump|cluster
2345 1 2 1 0
2345 2 8 12 2
3456 1 3 2 1
Many thanks, A.
回答1:
I was thinking that the order of the array must be re-ordered like in array.sort() but apparently it does not. The following worked for me.
clusters = kmeans.labels_
i=0
while(i < len(clusters)):
print(cookie_id[I],clusters[i])
i+=1
来源:https://stackoverflow.com/questions/57853038/how-to-export-the-output-cluster-labels-of-k-means-algorithm-with-the-ids-in-t