k means教程代码(聚类)


```python
# k means教程代码(聚类)
# 0.引入依赖
import numpy as np
import matplotlib.pyplot as plt
# 从sklearn中直接生成聚类数据
from sklearn.datasets.samples_generator import make_blobs
# 引入scipy中的距离函数,默认欧氏距离
from scipy.spatial.distance import cdist

# 1.数据加载
x, y = make_blobs(n_samples=100, centers=6, random_state=1234, cluster_std=0.6)


# print(x, y)
# plt.figure(figsize=(6, 6))
# plt.scatter(x[:, 0], x[:, 1], c=y)
# plt.show()


# 2.算法实现
class K_Means(object):
    # 初始化,参数 n_clusters 迭代次数max_iter、初始化质心 centroids
    def __init__(self, n_clusters=6, max_iter=100, centroids=[]):
        self.n_clusters = n_clusters
        self.max_iter = max_iter
        self.centroids = np.array(centroids, dtype=np.float)

    # 训练模型过程,k-means聚类过程,传入原始数据
    def fit(self, data):
        # 假设没有指定的初始质心,就随机选取data中的点作为初始质心
        if (self.centroids.shape == (0,)):
            # 从data中随机生成0到data行数的6个整数,作为索引值
            self.centroids = data[np.random.randint(0, data.shape[0], self.n_clusters), :]
        # 开始迭代
        for i in range(self.max_iter):
            # 1.计算距离矩阵,得到的是一个100*6的矩阵
            distances = cdist(data, self.centroids)
            # 2.对距离按有近到远排序,选取最近的质心点的类别,作为当前的分类
            c_ind = np.argmin(distances, axis=1)
            # 3.对每一类数据进行均值计算,更新质心点坐标
            for i in range(self.n_clusters):
                # 排除掉没有出现在c_ind里的类别
                if i in c_ind:
                    # 选出所有类别是i的点,取data里面的坐标的均值,更新第i个质心
                    self.centroids[i] = np.mean(data[c_ind == i], axis=0)

    # 实现预测方法
    def predict(self, samples):
        # 和上面一样,先计算距离矩阵,然后选取距离最近的那个质心的类别
        distances = cdist(samples, self.centroids)
        c_ind = np.argmin(distances, axis=1)

        return c_ind


# 3.测试
# 定义一个绘制子图的函数
def plotKMeans(x, y, centroids, subplot, title):
    # 分配子图,表示1行2列的子图
    plt.subplot(subplot)
    plt.scatter(x[:, 0], x[:, 1], c='r')
    # 画出质心点
    plt.scatter(centroids[:, 0], centroids[:, 1], c=np.array(range(6)), s=100)
    plt.title(title)
    plt.show()


kmeans = K_Means(max_iter=100, centroids=np.array([[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6]]))
plt.figure(figsize=(16, 6))
plotKMeans(x, y, kmeans.centroids, 121, 'initial State')
# 开始聚类
kmeans.fit(x)
plt.figure(figsize=(16, 6))
plotKMeans(x, y, kmeans.centroids, 122, 'Final State')

# 预测新数据点的类别

x_new = np.array([[0, 0], [10, 7]])
y_pred = kmeans.predict(x_new)
print(y_pred)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值