Why is KMeans a class rather than a function defined in sklearn?

Viewed 57

From developers' perspective, why did they design KMeans using a class and let people init it and use it like this:

from sklearn.cluster import KMeans
import numpy as np

X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)

Why not a function so that users can import and call it directly?

1 Answers

This is how the scikit-learn design pattern works, almost all of the models are classes, for each class, we have functions like predict, and fit.

In fact, for any machine learning model, there must be some internal states, weights for an MLP model for example, if you want to manage these states in a managed way, a class should be your first choice, not a function.

Related