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

如何在Scikit-learn KMeans中用预训练质心直接调用predict而不fit?

Scikit-learn中用预定义质心直接调用KMeans的predict方法

Scikit-learn的KMeans estimator必须完成拟合(调用过fit)才能调用predict,否则会抛出NotFittedError。要直接用预定义质心实现预测,有两种可靠方案:

方案一:手动设置模型拟合属性

直接给KMeans实例赋值预定义质心,并补充必要的拟合标记属性:

from sklearn.cluster import KMeans
import numpy as np

# 提取预定义质心
centroids = np.array(models['primary'])
n_clusters = centroids.shape[0]
n_features = centroids.shape[1]

# 初始化模型
kmeans = KMeans(n_clusters=n_clusters)
# 手动设置质心
kmeans.cluster_centers_ = centroids
# 新版本Scikit-learn需指定输入特征数,避免维度检查错误
kmeans.n_features_in_ = n_features

# 直接执行预测
predictions = kmeans.predict(inference_data)

方案二:用空数据快速执行fit(无计算开销)

通过设置max_iter=0和n_init=1,调用fit时传入空数据,让模型标记为已拟合但不修改质心:

from sklearn.cluster import KMeans
import numpy as np

# 提取预定义质心
centroids = np.array(models['primary'])
n_features = centroids.shape[1]

# 初始化模型,禁用迭代和重复初始化
kmeans = KMeans(init=centroids, n_clusters=len(centroids), n_init=1, max_iter=0)
# 传入空数据完成拟合标记,无实际聚类计算
kmeans.fit(np.empty((0, n_features)))

# 执行预测
predictions = kmeans.predict(inference_data)

两种方案都能实现目标:方案一更直接,方案二更贴合Scikit-learn的API设计,避免遗漏内部属性导致的潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:40:29