最小化所有点到中心点的距离之和:
M
i
n
∑
s
∈
S
d
i
s
t
(
s
,
c
)
Min \sum _{s\in S}dist(s,c)
Min∑s∈Sdist(s,c),其中
d
i
s
t
(
s
,
c
)
=
M
i
n
c
∈
C
d
i
s
t
a
n
c
e
(
s
,
c
)
dist(s,c) = Min _{c\in C} distance(s,c)
dist(s,c)=Minc∈Cdistance(s,c)
k-means
思路:
初始化:选择
k
k
k个中心点 - 注:若选择是k个地点的集合,则可以先参照步骤3算出相应的中心点
根据各个点到中心点的距离,重新划分k个cluster:
S
j
=
{
s
∣
d
i
s
t
a
n
c
e
(
s
,
c
)
=
min
i
=
1
,
2
,
.
.
.
,
k
d
i
s
t
a
n
c
e
(
s
,
c
i
)
}
S_j = \{s | distance(s,c) = \min _{i=1,2,...,k} distance(s,c_i)\}
Sj={s∣distance(s,c)=mini=1,2,...,kdistance(s,ci)}
根据新的clusters,重新计算中心:
k
i
=
∑
s
∈
S
i
s
∣
S
i
∣
k_i = \frac {\sum _{s \in S_i}s} {|S_i|}
ki=∣Si∣∑s∈Sis
重复2-3,知道中心点不再发生变化
代码:
defk_means(sites, k, init_centers):
centers = init_centers[:]whileTrue:
new_centers =[]
changed_centers =[]# Assign the center to the sitefor site in sites:
center = assign_center(centers, site)[1]
site.center = center
center.sites.append(site)# Recalculate centerfor center in centers:
new_center = cal_center(center.sites)
new_centers.append(new_center)if new_center.location != center.location:
changed_centers.append(new_center)iflen(changed_centers)==0:return centers
centers = new_centers[:]
Related Topic: Clustering 聚类问题定义k-means思考问题定义INPUT同中心选址问题OBJECTIVE最小化所有点到中心点的距离之和:Min∑s∈Sdist(s,c)Min \sum _{s\in S}dist(s,c)Min∑s∈Sdist(s,c),其中dist(s,c)=Minc∈Cdistance(s,c)dist(s,c) = Min _{c...