Issue
I am using jupyter notebook here is the kernel information
Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
I am using k-means clustering. When I cluster, the only color that is used is blue. This isn't a big problem with how it is set up at the moment, but I need to scale it up so the colors need to be different. I followed a tutorial, so I don't understand all of the code 100%. The code is below.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
x = [1,5,1.5,8,1,9]
y = [2,8,1.8,8,.6,11]
plt.scatter(x,y)
plt.show()
X = np.array([[1,2],[5,8],[1.5,1.8],[8,8],[1,.6],[9,11]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
print(centroids)
print(labels)
colors = ['r','b','y','g','c','m']
for i in range(len(X)):
print("coordinate:",X[i], "label:", labels[i])
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
plt.show()
plt.scatter(x,y)
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
plt.show()
I think my problem lies it this piece.
colors = ['r','b','y','g','c','m']
for i in range(len(X)):
print("coordinate:",X[i], "label:", labels[i])
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)
Solution
I was indeed mistaken. My previous solution was incorrect. I could finally take a decent look at the return of labels and centroids, and I think this should do what you asked.
You can give a sequence as an argument for the color= argument, so there's no need for the fol-loop
colors = ['r','b','y','g','c','m']
plt.scatter(x,y, color=[colors[l_] for l_ in labels], label=labels)
plt.scatter(centroids[:, 0],centroids[:, 1], color=[c for c in colors[:len(centroids)]], marker = "x", s=150, linewidths = 5, zorder = 10)
Answered By - Maarten Fabré
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.