机器学习实验------K-means聚类算法

第1关:计算欧几里得距离

任务描述

本关实现一个函数来计算欧几里得距离。

python 复制代码
# -*- coding: utf-8 -*-
import numpy as np
def euclid_distance(x1, x2):
    """计算欧几里得距离
    参数:
        x1 - numpy数组
        x2 - numpy数组
    返回值:
        distance - 浮点数,欧几里得距离
    """
    distance = 0
    #   请在此添加实现代码     #
    #********** Begin *********#
    distance = np.sqrt(np.sum(np.square(x1-x2)))
    #********** End ***********#
    return distance

第2关:计算样本的最近邻聚类中心

任务描述

本关实现一个函数来计算距离每个样本最近的簇中心。

python 复制代码
# -*- coding: utf-8 -*-
from distance import euclid_distance  # 假设euclid_distance函数已定义

def nearest_cluster_center(x, centers):
    """计算各个聚类中心与输入样本最近的
    参数:
        x - numpy数组
        centers - numpy二维数组
    返回值:
        cindex - 整数,簇中心的索引值,比如3代表分配x到第3个聚类中
    """
    cindex = -1
    min_distance = float('inf')  # 初始化最小距离为无穷大

    # 遍历所有聚类中心
    for i, center in enumerate(centers):
        # 计算当前聚类中心与样本x的欧几里得距离
        distance = euclid_distance(x, center)
        # 如果当前距离小于已知的最小距离,则更新最小距离和对应的聚类中心索引
        if distance < min_distance:
            min_distance = distance
            cindex = i

    return cindex

第3关:计算各聚类中心

编程任务

本关卡要求你实现函数 estimate_centers,在右侧编辑器 Begin-End 区间补充代码,

python 复制代码
# -*- coding: utf-8 -*-
import numpy as np

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]))
    
    # 为每个聚类创建一个列表来存储同类样本的索引
    clusters = {i: [] for i in range(n_clusters)}
    
    # 将样本分配到对应的聚类中
    for idx, label in enumerate(y_estimated):
        clusters[label].append(idx)
    
    # 计算每个聚类的均值,更新聚类中心
    for label, indices in clusters.items():
        centers[label] = np.mean(X[indices, :], axis=0)
    
    return centers

第4关:评估聚类效果

本关任务

本关实现准确度评估函数,来评估聚类算法的效果。

python 复制代码
# -*- coding: utf-8 -*-
import numpy as np  # 导入 NumPy 库

def acc(x1, x2):
    """计算精度
    参数:
        x1 - numpy数组
        x2 - numpy数组
    返回值:
        value - 浮点数,精度
    """
    # 确保x1和x2长度相同,如果不同则返回0.0
    if len(x1) != len(x2):
        return 0.0
    
    # 计算相等元素的数量
    correct_matches = np.sum(x1 == x2)
    
    # 计算精度
    value = correct_matches / len(x1)
    
    return value

第5关:组合已实现的函数完成K-means算法

本关任务

本关综合前面四个关卡的内容来实现K-means聚类算法。

python 复制代码
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from distance import euclid_distance
from estimate import estimate_centers
from loss import acc
from near import nearest_cluster_center

# 随机种子对聚类的效果会有影响,为了便于测试,固定随机数种子
np.random.seed(5)
# 读入数据集
dataset = pd.read_csv('./data/iris.csv')
# 取得样本特征矩阵
X = dataset[['150','4','setosa','versicolor']].as_matrix()
y = np.array(dataset['virginica'])
# 读入数据
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]]  # 初始聚类中心

# 开始算法流程
y_estimated = np.zeros(len(y), dtype=int)  # 确保y_estimated是整数类型

# ********** Begin *********#
for _ in range(n_iteration):
    # 分配步骤:将每个点分配给最近的聚类中心
    for i in range(len(y)):
        y_estimated[i] = nearest_cluster_center(X[i], cluster_centers)
    
    # 更新步骤:重新计算聚类中心
    new_centers = estimate_centers(X, y_estimated, n_clusters)
    cluster_centers = new_centers
# ********** End ***********#

# 计算精度
if len(y_estimated) > 0:  # 确保y_estimated不为空
    accuracy = acc(y_estimated, y)
    print('%.3f' % accuracy)
else:
    print("无法计算精度,y_estimated为空或长度为0。")
相关推荐
huapiaoy6 分钟前
Redis中数据类型的使用(hash和list)
redis·算法·哈希算法
冷白白19 分钟前
【C++】C++对象初探及友元
c语言·开发语言·c++·算法
鹤上听雷27 分钟前
【AGC005D】~K Perm Counting(计数抽象成图)
算法
一叶祇秋39 分钟前
Leetcode - 周赛417
算法·leetcode·职场和发展
武昌库里写JAVA44 分钟前
【Java】Java面试题笔试
c语言·开发语言·数据结构·算法·二维数组
ya888g1 小时前
GESP C++四级样题卷
java·c++·算法
Funny_AI_LAB1 小时前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
NuyoahC1 小时前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_1011 小时前
MATLAB中decomposition函数用法
开发语言·算法·matlab
zmjia1111 小时前
全流程Python编程、机器学习与深度学习实践技术应用
python·深度学习·机器学习