#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()
相关推荐
湘美书院--湘美谈教育10 分钟前
湘美书院人工智能访谈录:AI助力科学研究自动化
大数据·运维·人工智能·机器学习·自动化·电脑·生活
一碗白开水一12 分钟前
入门实践工程一:基于 sklearn 的鸢尾花分类(传统机器学习入门)|附:环境依赖及工程源码
机器学习·分类·sklearn
TechEdu20260620 分钟前
[人工智能]Scikit-learn:Python中的实用机器学习库
人工智能·机器学习·ai·scikit-learn
databook1 小时前
基于模型的重要性评分进行“特征排序”
python·机器学习·scikit-learn
404NotFOund1 小时前
小白本地部署微调耍起
机器学习·开源
具身新纪元3 小时前
CVPR 2026|新缺陷不断上线,如何让工业视觉检测模型不忘旧账?
人工智能·深度学习·目标检测·机器学习·计算机视觉·目标跟踪·视觉检测
only-qi3 小时前
大模型微调流程深度解析:从面试题到工程实践
人工智能·机器学习·ai·llm
一次旅行4 小时前
Ollama本地私有化大模型完整工程实战
人工智能·机器学习·github
小趴蔡ha12 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
小趴蔡ha18 小时前
04 Pandas 数据清洗实战:从表格读取到机器学习特征准备
人工智能·机器学习·pandas