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

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

任务描述

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

# -*- 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关:计算样本的最近邻聚类中心

任务描述

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

# -*- 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 区间补充代码,

# -*- 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关:评估聚类效果

本关任务

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

# -*- 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聚类算法。

# -*- 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。")


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不想做程序猿的员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值