第七章 分割聚类方法之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))
相关推荐
yzx9910133 分钟前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
亮亮爱刷题6 分钟前
算法练习-回溯
算法
眼镜哥(with glasses)1 小时前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
Blossom.1184 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
郄堃Deep Traffic6 小时前
机器学习+城市规划第十四期:利用半参数地理加权回归来实现区域带宽不同的规划任务
人工智能·机器学习·回归·城市规划
int型码农6 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT6 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面6 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked936 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
怀旧,6 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法