第七章 分割聚类方法之K-Means实现

比较烦人的是这一章是不能去复制的 怎么办呢?我之前写过一篇博客去解决这个问题
7行Python代码解决头歌 学习通等不能粘贴问题_头歌解除复制粘贴-CSDN博客

第1关:计算两点之间的距离

import numpy as np

def Distance_Euclid(x, y):
    '''
    input:x(ndarray):第一个样本的坐标
          y(ndarray):第二个样本的坐标
    output:distance(float):x到y的距离
    '''
    #********* Begin *********#
    return  np.power(np.sum(np.abs(x - y) ** 2), 1 / 2)
    # ********* End *********#
def Distance_Manhattan(x, y):
    '''
    input:x(ndarray):第一个样本的坐标
          y(ndarray):第二个样本的坐标
    output:distance(float):x到y的距离
    '''
    #********* Begin *********#
    return np.sum(np.abs(x - y))
    # ********* End *********#
def Distance_Chebyshev(x,y):
    '''
    input:x(ndarray):第一个样本的坐标
          y(ndarray):第二个样本的坐标
    output:distance(float):x到y的距离
    '''
    #********* Begin *********#
    return np.abs(x - y).max()
    #********** End *********#
def Distance_Minkowski(x,y,p):
    '''
    input:x(ndarray):第一个样本的坐标
          y(ndarray):第二个样本的坐标
          p(int):等于1时为曼哈顿距离,等于2时为欧氏距离
    output:distance(float):x到y的距离
    '''
    #********* Begin *********#
    return np.power(np.sum(np.abs(x - y) ** p), 1 / p)
    #********* End *********#

第2关:样本聚类 

# -*- coding: utf-8 -*-
import numpy as np

from Distance import Distance_Minkowski

def Nearest_Center(x, centers):
    """计算各个聚类中心与输入样本最近的
    参数:
        x - numpy数组
        centers - numpy二维数组
    返回值
        cindex - 整数类中心的索引值比如3代表分配x到第3个聚类中
    """
    cindex = -1
    #计算点到各个中心的距离
    distance_list = [Distance_Minkowski(x, center, 2) for center in centers]
    #找出最小距离的类
    cindex = np.argmin(distance_list)
    return cindex

def Estimate_Centers(X, y_estimated, n_clusters):
    """重新计算各聚类中心
    参数:
        X - numpy二维数组代表数据集的样本特征矩阵
        y_estimated - numpy数组估计的各个样本的聚类中心索引
        n_clusters - 整数设定的聚类个数
    返回值
        centers - numpy二维数组各个样本的聚类中心
    """
    centers = np.zeros((n_clusters, X.shape[1]))
    for i in range(n_clusters):
        cluster_points = X[y_estimated == i]
        centers[i] = np.mean(cluster_points, axis=0)
    return centers

第3关:K-Means算法实现 

#-*- coding: utf-8 -*-
import numpy as np
import pandas as pd

from Cluster import Nearest_Center
from Cluster import Estimate_Centers

def Cal_Accuracy(x1, x2):
    """计算精度
    参数:
        x1 - numpy数组
        x2 - numpy数组
    返回值
        value - 浮点数精度
    """
    #聚类数组对应元素相比较
    correct = np.sum(x1 == x2)  # 统计分类正确的样本数量
    accuracy = correct / len(x1)  # 计算分类正确的比例
    return accuracy

# 随机种子对聚类的效果会有影响为了便于测试固定随机数种子
np.random.seed(5)
# 读入数据集
dataset = pd.read_csv('K-Means/iris.csv')
# 取得样本特征矩阵
X = dataset[['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth']].values
y = np.array(dataset['Species'])
# 读入数据
n_clusters, n_iteration = input().split(',')  # 输入
n_clusters = int(n_clusters)  # 聚类中心个数
n_iteration = int(n_iteration)  # 迭代次数
# 随机选择若干点作为聚类中心
point_index_lst = np.arange(len(y))
np.random.shuffle(point_index_lst)
cluster_centers = X[point_index_lst[:n_clusters]]
# 开始算法流程
for iter in range(n_iteration):
    y_estimated = np.array([Nearest_Center(x, cluster_centers) for x in X])  # 计算各个点最接近的聚类中心
    cluster_centers = Estimate_Centers(X, y_estimated, n_clusters)  # 计算各个聚类中心
print('%.3f' % Cal_Accuracy(y_estimated, y))
  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
K-Means算法是一种常用的聚类方法,它将数据集分成K个簇,每个簇的数据点和簇内其他点的距离最小。下面我们来实现K-Means算法。 1. 首先随机选取K个中心点,可以根据数据集的分布情况来选取。 2. 对于每个数据点,计算它与K个中心点的距离,选择距离最近的中心点所在的簇,并将该数据点加入该簇。 3. 对于每个簇,重新计算该簇的中心点。 4. 重复步骤2-3,直到中心点不再发生变化或达到最大迭代次数。 下面是Python代码实现K-Means算法: ``` python import numpy as np class KMeans: def __init__(self, k=2, max_iter=100): self.k = k self.max_iter = max_iter def fit(self, X): # 随机选取k个中心点 self.centroids = X[np.random.choice(X.shape[0], self.k, replace=False)] for i in range(self.max_iter): # 计算每个数据点所属的簇 clusters = [[] for _ in range(self.k)] for x in X: dist = [np.linalg.norm(x - c) for c in self.centroids] cluster_idx = np.argmin(dist) clusters[cluster_idx].append(x) # 重新计算每个簇的中心点 new_centroids = np.zeros((self.k, X.shape[1])) for i, cluster in enumerate(clusters): if len(cluster) > 0: new_centroids[i] = np.mean(cluster, axis=0) else: new_centroids[i] = self.centroids[i] # 判断中心点是否发生变化 if np.allclose(self.centroids, new_centroids): break self.centroids = new_centroids def predict(self, X): dist = np.array([np.linalg.norm(X - c, axis=1) for c in self.centroids]) return np.argmin(dist, axis=0) ``` 以上就是K-Means算法的Python实现,可以通过fit方法对数据进行聚类,predict方法可以预测新的数据点所属的簇。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FindYou.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值