Python学习-Scipy库空间算法、数据结构
目录
1、快速查找最近邻点KDTree类:KDTree(data, leafsize)
2、凸壳计算(点集的边界计算)ConvexHull()
导入库
import scipy.spatial as spt
import matplotlib.pyplot as plt
import numpy as np
1、快速查找最近邻点KDTree类:KDTree(data, leafsize)
参数说明:
data: 指定一个(N,K)大小的二维数组,需要查找的数据点样本
leafsize: 切换到蛮力算法的点数,默认10
查询方法:
count_neighbors(other, r[,p]): 计算可以形成多少个附近点对
query(x[,k,eps,p,distance_upper_bound]): 查询最近邻点,k为返回的最近邻点数。返回值为d(距离),i(最近邻点的样本点中的顺序位置)
query_ball_point(x,r[,p,eps]): 查找点x的距离r内的所有点
query_ball_tree(other,r[,p,eps]): 查找距离最多为r的所有点对
query_pairs(r[,p,eps]): 查找距离内的所有点对
sparse_distance_matrix(other,max_distance): 计算稀疏矩阵距离
注:返回值i为点在样本点数组中的顺序位置
i
plt.rc('font', family='simhei', size=15) # 设置中文显示,字体大小
plt.rc('axes', unicode_minus=False) # 该参数解决负号显示的问题
point = np.array([[0, 2], [1.5, 3], [2, 4], [3, 5]]) # 二维样本点数组
kt = spt.KDTree(data=point, leafsize=10) # 用于快速查找的KDTree类
ckt = spt.cKDTree(point) # 用C写的查找类,执行速度更快
find_point = np.array([2, 2.5]) # 原点
d, x = kt.query(find_point) # 返回最近邻点的距离d和在数组中的顺序x
# 找出最近邻点的位置坐标
for i in range(len(point)):
if i == x:
fp = point[i]
print('最近邻点距离:', d)
print('最近邻点位置:', fp)
# 绘图展示
plt.scatter(x=point[:, 0], y=point[:, 1], s=20, c='g', marker='o') # 样本点
plt.scatter(x=find_point[0], y=find_point[1], s=30, c='b', marker='*')
plt.plot([fp[0], find_point[0]], [fp[1], find_point[1]], 'k--')
plt.text(x=1.8, y=2.8, s='最近距离:{}'.format('%.4f' % d)) # 保留小数点后4位
plt.show()
输出
最近邻点距离: 0.7071067811865476
最近邻点位置: [1.5 3. ]
2、凸壳计算(点集的边界计算)ConvexHull()
参数说明:
points: 散点样本
incremental: 是否允许逐步添加新点,默认False
qhull_options: 传递给Qhull的其他参数项
返回值:
simplices: 相邻两个外围点在样本点中的顺序对, 即相邻两个外围点在数组中的顺序
area:面积
point = np.random.randint(low=0, high=50, size=(50, 2))
# point = np.array([[6, 15], [13, 10], [1, 18], [4, 11], [14, 5], [12, 4], [4, 7], [9, 7], [4, 13], [3, 17]])
hull = spt.ConvexHull(points=point, incremental=False)
print('闭合范围内的面积:', hull.area)
# 绘制散点图
plt.scatter(x=point[:, 0], y=point[:, 1], marker='*', c='b')
for sim in hull.simplices:
# plt.plot([point[sim[0]][0], point[sim[1]][0]], [point[sim[0]][1], point[sim[1]][1]], 'g--')
plt.plot(point[sim, 0], point[sim, 1], 'red')
plt.show()
输出
闭合范围内的面积: 171.66706455014378