KMeans运行报错:'KMeans' object has no attribute 'intertia_',如何解决?
KMeans报错AttributeError: 'KMeans' object has no attribute 'intertia_' 解决方案
核心原因
触发报错的根本原因是属性名拼写错误:scikit-learn的KMeans类拟合完成后,存储所有样本到对应簇中心的距离平方和的属性为inertia_,你代码中拼写为intertia_,错误调换了字母t和r的顺序,调用不存在的属性因此触发报错。
修复后的代码
distortions=[] for k_val in k: kmeans=KMeans(n_clusters=k_val,max_iter=100) kmeans=kmeans.fit(img_vec) # 修正属性名拼写为inertia_ distortions.append(kmeans.inertia_)
额外注意事项
- 如果修正拼写后仍有报错,确认你导入的是scikit-learn官方的
sklearn.cluster.KMeans类,其他第三方库封装的同名KMeans类可能没有inertia_属性 - 你的
img_vec样本量较大,若运行速度偏慢,可给KMeans新增参数n_init='auto'(适配scikit-learn 1.2及以上版本),减少重复拟合次数提升运行效率
内容的提问来源于stack exchange,提问作者srv_77
相关产品推荐
相关产品推荐

