3
我在大型numpy
数组中具有许多不同的形式,我想使用numpy
和scipy
来计算它们之间的边到边的欧氏距离。numpy数组中标记组件之间的最小边对边欧氏距离
注意:我做了搜索,这是从现在开始堆以前其它问题不同,因为我想获得一个阵列中,而不是点或单独阵列之间的标记斑块之间的最小距离为其他问题都问。
我目前的方法使用KDTree,但对于大型阵列来说效率非常低。本质上,我正在查找每个标记组件的坐标并计算所有其他组件之间的距离。最后,以平均最小距离为例进行计算。
我正在寻找一个更聪明的方法使用python,最好没有任何额外的模块。
import numpy
from scipy import spatial
from scipy import ndimage
# Testing array
a = numpy.zeros((8,8), dtype=numpy.int)
a[2,2] = a[3,1] = a[3,2] = 1
a[2,6] = a[2,7] = a[1,6] = 1
a[5,5] = a[5,6] = a[6,5] = a[6,6] = a[7,5] = a[7,6] = 1
# label it
labeled_array,numpatches = ndimage.label(a)
# For number of patches
closest_points = []
for patch in [x+1 for x in range(numpatches)]:
# Get coordinates of first patch
x,y = numpy.where(labeled_array==patch)
coords = numpy.vstack((x,y)).T # transform into array
# Built a KDtree of the coords of the first patch
mt = spatial.cKDTree(coords)
for patch2 in [i+1 for i in range(numpatches)]:
if patch == patch2: # If patch is the same as the first, skip
continue
# Get coordinates of second patch
x2,y2 = numpy.where(labeled_array==patch2)
coords2 = numpy.vstack((x2,y2)).T
# Now loop through points
min_res = []
for pi in range(len(coords2)):
dist, indexes = mt.query(coords2[pi]) # query the distance and index
min_res.append([dist,pi])
m = numpy.vstack(min_res)
# Find minimum as closed point and get index of coordinates
closest_points.append(coords2[m[numpy.argmin(m,axis=0)[0]][1]])
# The average euclidean distance can then be calculated like this:
spatial.distance.pdist(closest_points,metric = "euclidean").mean()
编辑 只是测试@morningsun提出的解决方案,这是一个巨大的速度提升。但是返回的值略有不同:
# Consider for instance the following array
a = numpy.zeros((8,8), dtype=numpy.int)
a[2,2] = a[2,6] = a[5,5] = 1
labeled_array, numpatches = ndimage.label(cl_array,s)
# Previous approach using KDtrees and pdist
b = kd(labeled_array,numpatches)
spatial.distance.pdist(b,metric = "euclidean").mean()
#> 3.0413115592767102
# New approach using the lower matrix and selecting only lower distances
b = numpy.tril(feature_dist(labeled_array))
b[b == 0 ] = numpy.nan
numpy.nanmean(b)
#> 3.8016394490958878
EDIT 2
啊,想通了。 spatial.distance.pdist不返回适当的距离矩阵,因此这些值是错误的。
感谢您的支持!我只是在我的一个数据集上进行了测试,运行速度快了近89%。矢量化的力量。虽然我不完全理解为什么'sqeuclidean'被计算出来。如果尝试计算所有差异的均值(例如,请参阅编辑),它也会返回不同的值。 – Curlew
啊,想通了(见上文)。 Pdist不会返回适当的距离矩阵,因此我以前的值错误...再次感谢您的解决方案! – Curlew
@Curlew - 平方欧几里得计算速度更快。请注意,我仅将它用于中间结果;平方根在return语句中被采用。 – 2016-05-14 19:52:29