我在某些行的位置做了一些安排,现在代码看起来像这样
from mpl_toolkits.mplot3d import Axes3D
def elbow_plot(data, maxK=40, seed_centroids=None):
sse = {}
for k in range(1, maxK):
print("k:", k)
if seed_centroids is not None:
seeds = seed_centroids.head(k)
kmeans = KMeans(n_clusters = k, max_inter= 500, n_init=100, random_state=0, init=np.reshape(seeds, (k,1))).fit(data)
data["clusters"] = kmeans.labels_
else:
kmeans = KMeans(n_clusters=k, max_iter=300, n_init=100, random_state=0).fit(data)
data["clusters"] = kmeans.labels_
sse[k] = kmeans.inertia_
plt.figure()
plt.plot(list(sse.keys()), list(sse.values()))
plt.show()
return
elbow_plot(X, maxK=10)
所以我做了一些更改。现在会弹出该错误
NameErrorTraceback (most recent call last)
<ipython-input-100-69e2bdc4db8e> in <module>()
9 """
10 sse = {}
---> 11 for k in range(1, maxK):
12 print("k:", k)
13 if seed_centroids is not None:
NameError: name 'maxK' is not defined
答案 0 :(得分:0)
from mpl_toolkits.mplot3d import Axes3D
def elbow_plot(data, maxK=40, seed_centroids=None):
sse = {}
for k in range(1, maxK):
print("k: ", k)
if seed_centroids is not None:
seeds = seed_centroids.head(k)
kmeans = KMeans(n_clusters=k, max_iter=500, n_init=100, random_state=0, init=np.reshape(seeds,
(k,1))).fit(data)
data["clusters"] = kmeans.labels_
else:
kmeans = KMeans(n_clusters=k, max_iter=300, n_init=100, random_state=0).fit(data)
data["clusters"] = kmeans.labels_
# Inertia: Sum of distances of samples to their closest cluster center
sse[k] = kmeans.inertia_
plt.figure()
plt.plot(list(sse.keys()), list(sse.values()))
plt.show()
return
elbow_plot(X, maxK=10)
尝试运行此程序。 它们似乎与plt.figure()中的缩进有关。
请确保for循环在函数内,因为您的函数正在返回内容。因此,请在此代码段for k in range(1, maxK):