You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用KMeans聚类方法报kmeans未定义及语法错误求助

问题根因
  • 代码中KMeans类实例化语句缺少闭合右括号),触发语法错误,导致kmeans变量未被成功创建,后续所有调用kmeans的语句都会抛出NameError
  • 代码中存在重复导入语句,虽不影响运行,但属于冗余内容可清理
修复方案

仅需要在KMeans实例化的参数末尾添加右括号即可,完整修复后的代码如下:

import matplotlib.pyplot as plt
#from kneed import KneeLocator
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

#generate some data with make_blob()
features, true_labels = make_blobs(
n_samples=200,
centers=3,
cluster_std=2.75,
random_state=42
)

#show the features
features[:5]
#first 5 elements for each variable
true_labels[:5]

#scale the features
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)

#show the features
scaled_features[:5]

kmeans = KMeans(
     init="random",
     n_clusters=3,
     n_init=10,
     max_iter=300,
     random_state=42
)

kmeans.fit(scaled_features) 

#The lowest SSE value
kmeans.inertia_ 

#Final locations of the centroid
kmeans.cluster_centers_

kmeans.n_iter_

kmeans.labels_[:5]

修改后运行即可正常返回聚类结果,无语法和变量未定义报错。

内容的提问来源于stack exchange,提问作者Psiberian_Mushky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:36:01