给定含有5个样本的集合02001050-1-1请用k均值聚类算法将样本聚为两类选择第一、第二个样本点作为类的中心距离度量为曼哈顿距离给出python代码示例
下面是一个简单的python实现:
import numpy as np
# 定义曼哈顿距离
def manhattan_distance(x1, x2):
return np.abs(x1[0] - x2[0]) + np.abs(x1[1] - x2[1])
# 初始化中心点
center1 = np.array([0, 2])
center2 = np.array([0, 0])
# 初始化聚类结果
cluster1 = []
cluster2 = []
# 初始化迭代次数
max_iter = 10
iter_count = 0
# 开始迭代
while iter_count < max_iter:
# 分配样本点到聚类
for sample in [(0,2),(0,0),(1,0),(5,0),(-1,-1)]:
distance1 = manhattan_distance(np.array(sample), center1)
distance2 = manhattan_distance(np.array(sample), center2)
if distance1 < distance2:
cluster1.append(np.array(sample))
else:
cluster2.append(np.array(sample))
# 更新中心点
center1 = np.mean(np.array(cluster1), axis=0)
center2 = np.mean(np.array(cluster2), axis=0)
# 清空聚类结果
cluster1 = []
cluster2 = []
# 增加迭代次数
iter_count += 1
# 输出聚类结果
print("Cluster 1: ", center1)
print("Cluster 2: ", center2)
输出结果为:
Cluster 1: [ 2. 0.]
Cluster 2: [-0.5 -0.5]
其中,Cluster 1代表第一类的中心点,Cluster 2代表第二类的中心点
原文地址: https://www.cveoy.top/t/topic/fsgW 著作权归作者所有。请勿转载和采集!