2017年2月18日 K-means

本文介绍了一种K-means聚类算法的实现过程,包括样本分配和中心更新两个迭代步骤,直至分配不再变化。通过使用Python和NumPy库,文章展示了如何从鸢尾花数据集中加载数据,并进行聚类分析。

K-means clustering aims to partition the samples into k sets so as to miniize the sum of distances between each pointer to the K center
The algorithm proceeds by iterating two steps: cluster assignment step and center update step, until assignments no longer change.

from __future__ import division
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt 
%matplotlib inline

data = load_iris()
X = data.data
y = data.target

class myKMean:
    
    def compute_centers(self, X, predict, n_clusters):
        centers = []
        for c in range(n_clusters):
            centers.append(np.mean(X[np.where(predict == c)], axis=0))

        return np.array(centers)
    
    def compute_cluster(self, X, centers):
        predict = []
        for x in X:
            distances = [ np.sqrt(np.sum((x-c)**2)) for c in centers]
            predict.append(np.argmin(distances))

        return np.array(predict)
    
    def fit(self, X, n_clusters):
        predict = np.random.randint(n_clusters, size=X.shape[0])
        
        while True:
            self.centers = self.compute_centers(X, predict, n_clusters)
            p = self.compute_cluster(X, self.centers)
            
            if np.count_nonzero(predict - p) == 0:
                break
            else:
                predict = p
            
    def predict(self, X):
        return self.compute_cluster(X, self.centers)
        
km = myKMean()
km.fit(X, len(np.unique(y)))

for i in range(data.target_names.shape[0]):
    Xi = X[np.where(y == i)]
    plt.scatter(Xi[:,0], Xi[:,1])
    
plt.scatter(km.centers[:,0], km.centers[:,1], marker='x')

转载于:https://my.oschina.net/airxiechao/blog/862755

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值