import random
from kmeans_tools import Cluster, get_distance, gen_random_sample
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
def kmeans(samples, k, cutoff):
"""
kmeans函数
"""
init_samples = random.sample(samples, k)
clusters = [Cluster([sample]) for sample in init_samples]
n_loop = 0
while True:
lists = [[] for _ in clusters]
n_loop += 1
for sample in samples:
smallest_distance = get_distance(sample, clusters[0].centroid)
cluster_index = 0
for i in range(k - 1):
distance = get_distance(sample, clusters[i+1].centroid)
if distance < smallest_distance:
smallest_distance = distance
cluster_index = i + 1
lists[cluster_index].append(sample)
biggest_shift = 0.0
for i in range(k):
shift = clusters[i].update(lists[i])
biggest_shift = max(biggest_shift, shift)
if biggest_shift < cutoff:
print("第{}次迭代后,聚类稳定。".format(n_loop))
break
return clusters
def run_main():
"""
主函数
"""
n_samples = 1000
n_feat = 2
lower = 0
upper = 200
n_cluster = 5
samples = [gen_random_sample(n_feat, lower, upper) for _ in range(n_samples)]
cutoff = 0.2
clusters = kmeans(samples, n_cluster, cutoff)
for i, c in enumerate(clusters):
for sample in c.samples:
print('聚类--{},样本点--{}'.format(i, sample))
plt.subplot()
color_names = list(mcolors.cnames)
for i, c in enumerate(clusters):
x = []
y = []
random.choice
color = [color_names[i]] * len(c.samples)
for sample in c.samples:
x.append(sample.coords[0])
y.append(sample.coords[1])
plt.scatter(x, y, c=color)
plt.show()
if __name__ == '__main__':
run_main()
import math
import random
class Cluster(object):
"""
聚类
"""
def __init__(self, samples):
if len(samples) == 0:
raise Exception("错误:一个空的聚类!")
self.samples = samples
self.n_dim = samples[0].n_dim
for sample in samples:
if sample.n_dim != self.n_dim:
raise Exception("错误: 聚类中样本点的维度不一致!")
self.centroid = self.cal_centroid()
def __repr__(self):
"""
输出对象信息
"""
return str(self.samples)
def update(self, samples):
"""
计算之前的聚类中心和更新后聚类中心的距离
"""
old_centroid = self.centroid
self.samples = samples
self.centroid = self.cal_centroid()
shift = get_distance(old_centroid, self.centroid)
return shift
def cal_centroid(self):
"""
对于一组样本点计算其中心点
"""
n_samples = len(self.samples)
coords = [sample.coords for sample in self.samples]
unzipped = zip(*coords)
centroid_coords = [math.fsum(d_list)/n_samples for d_list in unzipped]
return Sample(centroid_coords)
class Sample(object):
"""
样本点类
"""
def __init__(self, coords):
self.coords = coords
self.n_dim = len(coords)
def __repr__(self):
"""
输出对象信息
"""
return str(self.coords)
def get_distance(a, b):
"""
返回样本点a, b的欧式距离
参考:https://en.wikipedia.org/wiki/Euclidean_distance#n_dimensions
"""
if a.n_dim != b.n_dim:
raise Exception("错误: 样本点维度不同,无法计算距离!")
acc_diff = 0.0
for i in range(a.n_dim):
square_diff = pow((a.coords[i]-b.coords[i]), 2)
acc_diff += square_diff
distance = math.sqrt(acc_diff)
return distance
def gen_random_sample(n_dim, lower, upper):
"""
生成随机样本
"""
sample = Sample([random.uniform(lower, upper) for _ in range(n_dim)])
return sample