---
title: "k-means算法"
author: "googya"
date: "2010-06-28T14:25:58Z"
tags: ["C", "C#", "C++", "Ruby", "算法"]
categories: ["编程语言"]
slug: "k-means"
draft: false
lastmod: "2010-06-28T14:25:58Z"
id: 700851
url: "https://googya.iteye.com/blog/700851"
---

k-means聚类以k个（也是要聚类的个数）随机的中心质点（centroid）开始，然后将每个待聚类的项分派到离它最近的簇。分派完之后，中心质点要进行移动：移动到该簇所有点的平均位置上。接着再次进行分配。这个过程反复的执行，直到中心质点的位置不再发生明显变化或者说分配后的点所属的簇不在变化。 具体来说是以下四步： \[list] \[\*](1) Start with k cluster centers (chosen randomly or according to some specific procedure). \[/list] \[list] \[\*](2) Assign each row in the data to its nearest cluster center. \[/list] \[list] \[\*](3) Re-calculate the cluster centers as the "average" of the rows in (2). \[/list] \[list] \[\*](4) Repeat, until the cluster centers no longer change or some other stopping criterion has been met. \[/list] 代码如下： \[code="Ruby"] require 'mathn' class Point#点的类：坐标及维度 attr :coords,:n def initialize(coords) @coords=coords @n=coords.size end def to\_s @coords.to\_s end end class Cluster attr :points,:n,:centroid#簇类：点的集合，维度，中心质点 def initialize(points) if points.size==0 raise "ILLEGAL:EMPTY CLUSTER" end @points=points @n=points\[0].n for p in points if p.n!=@n raise "ILLEGAL: MULTISPACE CLUSTER" end end @centroid=calculateCentroid() end def update(points) old\_centroid=@centroid @points=points @centroid=calculateCentroid() getDistance(old\_centroid,@centroid) end def calculateCentroid centroid\_coords=\[] for i in 0..@n-1 centroid\_coords&lt;&lt;0.0 for p in @points centroid\_coords\[i] = centroid\_coords\[i]+p.coords\[i] end centroid\_coords\[i] = centroid\_coords\[i]/@points.size end Point.new(centroid\_coords) end def to\_s @points end end def kmeans(points,k,cutoff) initial=\[] clusters=\[] k.times do initial&lt;shift)?biggest\_shift : shift end if biggest\_shift