第七章 分割聚类方法之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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

FindYou.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值