Python代码语法问题咨询:NameError: maxK未定义错误排查
Let's walk through resolving the issues in your code, starting with the immediate NameError and moving to other critical problems:
1. Immediate Fix: maxK is not defined Error
The error occurs because the loop for k in range(1, maxK): was running in the global scope (not inside the function) where maxK wasn't declared. Ensure all code under elbow_plot is properly indented under the function definition. When calling the function, pass your data and optionally maxK (e.g., elbow_plot(X, maxK=10)).
2. Missing Required Imports
Your code uses libraries that aren't imported. Add these at the top of your script:
from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt
3. Typo in KMeans Parameter
You wrote max_inter=500 instead of max_iter=500 (missing an 'e'). This would throw a TypeError because KMeans doesn't recognize max_inter. Correct this parameter name.
4. Unnecessary Recursive Call & Undefined X
The line return elbow_plot(X, maxK=10) at the end of the function causes two issues:
Xis not defined inside the function (relying on a global variable is bad practice).- This creates infinite recursion—every time the function runs, it calls itself again. Remove this line entirely, or return the
ssedictionary if you need to analyze the values later.
5. Avoid Modifying Input Data
Assigning data["clusters"] = kmeans.labels_ alters the original DataFrame passed to the function. If you don't want to modify your input, create a copy first:
data_copy = data.copy() data_copy["clusters"] = kmeans.labels_
Or skip storing labels entirely (you only need kmeans.inertia_ for the elbow plot).
Corrected Full Code
Here's the fixed version with all issues addressed:
from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt def elbow_plot(data, maxK=40, seed_centroids=None): sse = {} # Adjust range to range(1, maxK+1) if you want to include maxK as the last value 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_copy = data.copy() data_copy["clusters"] = kmeans.labels_ else: kmeans = KMeans(n_clusters=k, max_iter=300, n_init=100, random_state=0).fit(data) data_copy = data.copy() data_copy["clusters"] = kmeans.labels_ sse[k] = kmeans.inertia_ plt.figure() plt.plot(list(sse.keys()), list(sse.values())) plt.xlabel("Number of Clusters (k)") plt.ylabel("Sum of Squared Errors (SSE)") plt.title("Elbow Plot for K-Means Clustering") plt.show() # Return SSE values for further analysis if needed return sse # Example usage (replace X with your actual dataset) # sse_results = elbow_plot(X, maxK=10)
How to Use
- Ensure your data
Xis a properly formatted DataFrame or numpy array for K-Means. - Call the function with your data and desired maximum cluster count:
elbow_plot(your_data, maxK=10)
内容的提问来源于stack exchange,提问作者Nat

