Python: 计算点集到最近中心点的距离及分类
Python: 计算点集到最近中心点的距离及分类
本篇博客将介绍如何使用 Python 和 NumPy 计算点集到多个中心点中最近的一个的距离,并将点分类到对应的中心点类别下,最后计算平均距离。
代码实现
import numpy as np
# 计算两点之间的距离
def distance(pt1, pt2):
return np.linalg.norm(pt1 - pt2)
# 计算当前各个中心点中离给定点 pt 最近的一个
def classify(pt, centers):
temp = [distance(pt, centers[i]) for i in range(len(centers))]
index = np.argmin(temp)
dist = temp[index]
return (index, dist)
# 示例数据
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
centers = np.array([[2, 3], [6, 7]])
categories = [[] for _ in range(len(centers))]
# 将每个点归入到离它最近的中心点类别下
########## Begin ##########
distances = []
for i in range(len(X)):
pt = X[i]
index, dist = classify(pt, centers)
distances.append(dist)
categories[index].append(pt)
# 将 pt 纳入离它最近的中心点类别下
# 计算每个点到离它最近的中心点的平均距离
avg_distance = np.mean(distances)
########## End ##########
print(f'分类结果: {categories}')
print(f'平均距离: {avg_distance}')
代码解读
distance(pt1, pt2)函数: 计算两点 pt1 和 pt2 之间的欧氏距离。classify(pt, centers)函数: 计算给定点 pt 到多个中心点 centers 中最近的一个中心点的索引和距离。- 代码块
Begin和End之间:- 遍历点集
X中的每个点pt。 - 调用
classify()函数获取pt到最近中心点的索引index和距离dist。 - 将距离
dist添加到列表distances中。 - 将点
pt添加到对应类别categories[index]中。
- 遍历点集
avg_distance = np.mean(distances): 计算所有距离的平均值,即平均距离。
总结
本篇博客介绍了如何使用 Python 和 NumPy 计算点集到多个中心点中最近的一个的距离,并将点分类到对应的中心点类别下,最后计算平均距离。该方法可应用于聚类分析、机器学习等领域。
原文地址: https://www.cveoy.top/t/topic/jpXY 著作权归作者所有。请勿转载和采集!