Why weights dont change K-mean cluster center position in sci-kit learn package?

Viewed 965

I am trying to calculate center position of a cluster with weights option. But weights seems not to work.

Here is the simple script which represent the problem

X = []
weights = []
for x in range(-10,10):
    for y in range(-10,10):
        X+= [[x,y]]
        if x>0 and y>0:
            weights += [10000]
        else:
            weights += [1]

X = np.array(X)
weights = np.array(weights)

kmeans = KMeans(n_clusters=1, random_state=0).fit(X,weights)
print kmeans.cluster_centers_

It prints [[-0.5 -0.5]] with weights 10000 in the 1st quarter.

I expect it to be approx (5,5)

EDIT1: Trying to call fit() as:

fit(X,sample_weight=weights)

Returns:

TypeError: fit() got an unexpected keyword argument 'sample_weight'

Adding second variable, does not help either:

fit(X,None,weights)

Returns:

TypeError: fit() takes at most 3 arguments (4 given)
1 Answers

The problem is in the way you call the fit method. You need to pass the weights as a keyword argument

kmeans = KMeans(n_clusters=1, random_state=0).fit(X, sample_weight=weights)

Explanation:

The signature of the fit method is the following:

KMeans.fit(self, X, y=None, sample_weight=None)

By calling KMeans.fit(self, X, weights) then implicitly y = weights. And since y is ignored there is no effect.

See official docs for more info.

Related