新彩天欢迎您!
幻海优品

Python SciPy 空间数据(Spatial Data)

1、处理空间数据

空间数据是指在几何空间中表示的数据。

例如。点在坐标系上。

我们处理许多任务上的空间数据问题。

例如。查找点是否在边界内。

SciPy为我们提供了scipy.spatial模块,该模块具有处理空间数据的功能。

2、三角测量法

多边形的三角剖分是将多边形划分为多个三角形,通过它们我们可以计算多边形的面积。

带点的三角剖分意味着创建表面组成的三角形,其中所有给定点都位于表面上任何三角形的至少一个顶点上。

通过点生成这些三角剖分的一种方法是Delaunay()三角剖分。

例如: 

从以下几点创建三角剖分:

import numpy as npfrom scipy.spatial import Delaunayimport matplotlib.pyplot as pltpoints = np.array([[2, 4],[3, 4],[3, 0],[2, 2],[4, 1]])simplices = Delaunay(points).simplicesplt.triplot(points[:, 0], points[:, 1], simplices)plt.scatter(points[:, 0], points[:, 1], color='r')plt.show()

Result:

httpswwwwonherocom

注意:simplices属性创建三角形符号的概括。

3、Convex Hull

凸包是覆盖所有给定点的最小多边形。

使用ConvexHull()方法创建一个凸包。

例如:

为以下几点创建凸包:

import numpy as npfrom scipy.spatial import ConvexHullimport matplotlib.pyplot as pltpoints = np.array([[2, 4],[3, 4],[3, 0],[2, 2],[4, 1],[1, 2],[5, 0],[3, 1],[1, 2],[0, 2]])hull = ConvexHull(points)hull_points = hull.simplicesplt.scatter(points[:,0], points[:,1])for simplex in hull_points:plt.plot(points[simplex,0], points[simplex,1], 'k-')plt.show()

 Result:

httpswwwwonherocom

4、KDTrees

KD树是为最近邻居查询优化的数据结构。

例如。在使用KDTree的一组点中,我们可以有效地询问哪些点最接近某个给定点。

KDTree()方法返回一个KDTree对象。

query()方法返回到最近邻居的距离和邻居的位置。

例如: 

找到最近的邻居指向(1,1):

from scipy.spatial import KDTreepoints = [(1, -1), (2, 3), (-2, 3), (2, -3)]kdtree = KDTree(points)res = kdtree.query((1, 1))print(res)

Result:

 (2.0, 0)

5、距离矩阵

在数据科学中,有很多距离度量用于查找两点之间的各种类型的距离,例如,欧几里得距离,余弦距离等。

两个向量之间的距离不仅可以是它们之间的直线长度,还可以是它们之间的原点角度或所需的单位步长等。

许多机器学习算法的性能在很大程度上取决于距离矩阵。例如, "K Nearest Neighbors", 或 "K Means"等。

让我们看一些距离度量:

6、欧氏距离

找到给定点之间的欧几里得距离。

例如:

from scipy.spatial.distance import euclideanp1 = (1, 0)p2 = (10, 2)res = euclidean(p1, p2)print(res)

 Result:

9.21954445729

7、城市街区距离(曼哈顿距离)

是使用4度移动量计算的距离。

例如。我们只能移动:向上,向下,向右或向左移动,不能沿对角线移动。

例如:

找到给定点之间的街区距离:

from scipy.spatial.distance import cityblockp1 = (1, 0)p2 = (10, 2)res = cityblock(p1, p2)print(res)

 Result:

11

8、余弦距离

是两个点A和B之间的余弦角值。

例如: 

找到给定点之间的余弦距离:

from scipy.spatial.distance import cosinep1 = (1, 0)p2 = (10, 2)res = cosine(p1, p2)print(res)

Result:

 0.019419324309079777

9、汉明距离

是两个比特不同的比特比例。

这是一种测量二进制序列距离的方法。

例如: 

找到给定点之间的汉明距离:

from scipy.spatial.distance import hammingp1 = (True, False, True)p2 = (False, True, True)res = hamming(p1, p2)print(res)

Result:

0.666666666667

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除