#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()
相关推荐
TAN-90°-14 分钟前
Deep Learning for Computer Vision——Generative Models 1
人工智能·深度学习·神经网络·目标检测·机器学习·计算机视觉
胡家伟++18 分钟前
从“过滤”到“选择”:投机解码、拒绝采样与强化学习的方差缩减统一理论
人工智能·机器学习
m0_5873830021 分钟前
上海24小时自助健身房系统软件开发实战指南:从架构到部署
人工智能·小程序·数据挖掘·系统架构·需求分析
雾屿_Mistisle1 小时前
模型窃取与隐私泄露(一)成员推断攻击
机器学习·数据分析
明志数科14 小时前
具身智能产业基础设施换挡:从算力本体到数据层的技术逻辑
人工智能·机器学习
tellmewhoisi17 小时前
机器学习:集成学习1(思想,Bagging,Boosting,随机森林和boosting之adaboost)
机器学习
码农幻想梦19 小时前
机器学习(一)
机器学习
ZPC821019 小时前
YOLO26 识别串番茄果梗
人工智能·深度学习·算法·机器学习
Rocky Ding*19 小时前
【三年面试五年模拟】2026-09-16 字节跳动 Agent 秋招一面全解析:从 Harness、记忆与并发到算法题的系统化解析
论文阅读·人工智能·深度学习·机器学习·aigc·ai-native·ai agent