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

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

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

python 复制代码
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关:样本聚类

python 复制代码
# -*- 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算法实现

python 复制代码
#-*- 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))
相关推荐
PPPPPaPeR.1 小时前
TopK问题与堆排序
c语言·开发语言·c++·算法
Recitative1 小时前
python单元测试入门
人工智能·python·深度学习·机器学习·单元测试
小森( ﹡ˆoˆ﹡ )1 小时前
【neo4j图数据库】入门实践篇
数据库·人工智能·机器学习·nlp·neo4j
鑫宝Code2 小时前
【机器学习】基于层次的聚类方法:理论与实践
人工智能·机器学习·聚类
卡戎-caryon2 小时前
【数据结构】06.栈&&队列
c语言·数据结构·算法·链表
山脚ice2 小时前
【CT】LeetCode手撕—704. 二分查找
算法·leetcode
贱贱的剑3 小时前
【算法】选择排序
算法·rust·排序算法
瑜陀3 小时前
2024.06.30 刷题日记
数据结构·算法·leetcode
Star Patrick3 小时前
*算法训练(leetcode)第二十天 | 39. 组合总和、40. 组合总和 II、131. 分割回文串
c++·算法·leetcode
光久li3 小时前
【算法刷题 | 动态规划14】6.28(最大子数组和、判断子序列、不同的子序列)
算法·动态规划