第七章 分割聚类方法之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))
相关推荐
计算机小白一个2 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^2 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
大数据追光猿4 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!4 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉4 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生4 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴5 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing5 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财5 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程5 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛