#P4475.第2题-终端款型聚类识别

第2题-终端款型聚类识别 - problem_ide - CodeFun2000

python 复制代码
import sys
import numpy as np

def solve():
    # 读取数据
    input_data = sys.stdin.read().strip().split()
    if not input_data:
        return

    k = int(input_data[0])
    m = int(input_data[1])
    n = int(input_data[2])

    # 将数据 reshape 成了 (m, 4) 的矩阵!
    data = np.array(input_data[3:], dtype=np.float64).reshape(m, 4)

    # 1. 初始化质心 (前 k 个点)
    centers = data[0:k].copy()

    # np.full(shape, fill_value, dtype)
    # np.zeros(shape, dtype)

    labels = np.zeros(m,dtype=int)

    for stap in range(n):
        old_centers = centers.copy()

        for i in range(m):
            distances = np.zeros(k)

            for j in range(k):
                dist = np.sqrt(np.sum((data[i]-old_centers[j] )**2))
                distances[j] = dist
            
            labels[i] = np.argmin(distances)
        
        
        # 更新质心
        for j in range(k):
            cluster = data[labels==j]

            if len(cluster)>0:
                centers[j] = np.mean(cluster,axis=0)
        
        max_shift = 0
        # 检查是否收敛 (质心不怎么动了)
        for j in range(k):
            shift = np.sqrt(np.sum((centers[j]-old_centers[j] )**2))
            if shift>max_shift:
                max_shift = shift

        if max_shift<1e-8:
            break

    counts = []
    for i in range(k):
        counts.append(np.sum(labels==i))
    
    counts.sort()
    print(" ".join(map(str,counts)))

if __name__ =='__main__':
    solve()
相关推荐
Lihua奏1 小时前
# 机器学习:机器是怎么从数据里学出规则的
机器学习
饼干哥哥6 小时前
用AI全自动剪辑,日更 100条爆款视频——HyperFrames、Remotion、Git使用入门
人工智能·机器学习·ai编程
魏祖潇1 天前
我在飞书里养了个“分身”——私聊喊它办事,群里 @ 它干活,还能替我传话
人工智能·机器学习
哥布林学者7 天前
深度学习进阶(三十一)FlashAttention:IO 感知的精确注意力
机器学习·ai
通信小呆呆9 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
xiao5kou4chang6kai49 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理