使用 sklearn KMeans 和预定义的聚类质心

问题描述 投票:0回答:1

我想将

init
关键字与一些预定义的集群质心一起使用:

from sklearn.cluster import KMeans

KMeans(n_clusters=10, init=np.random.randn(10, 3))

clf.predict(np.random.randn(3))

但我想将它们作为数组传递,而不是作为 Callable

上面的代码抛出错误:

NotFittedError:此 KMeans 实例尚未安装。在使用此估计器之前,请使用适当的参数调用“fit”。

我可以尝试拨打

fit()
,但没有数据怎么办?所有这些都不起作用:

clf.fit()
clf.fit(None)
clf.fit([])
clf.fit([[]])

设置

max_iter=0
也会产生错误。

执行此操作的正确方法是什么 - 最好不要触及类内部,如

clf._cluster_centers
等?

python scikit-learn k-means
1个回答
0
投票
import numpy as np
from sklearn.cluster import KMeans

# Example centroids
initial_centroids = np.random.randn(10, 3)  # 10 clusters, 3 features

# Create the KMeans instance with initial centroids
clf = KMeans(n_clusters=10, init=initial_centroids, n_init=1)

# Generate some sample data to fit (this should be real data in practice)
sample_data = np.random.randn(100, 3)  # 100 data points, 3 features

# Fit the model on the data
clf.fit(sample_data)

# Now you can predict new points
predictions = clf.predict(np.random.randn(3, 3))  # 3 new data points
print(predictions)

n_init=1
确保 KMeans 算法仅使用您指定的
init
质心运行一次,并且不会尝试其他随机初始化。

© www.soinside.com 2019 - 2024. All rights reserved.