python - Python中的平均最近坐标

标签 python arrays numpy

这是我的 previous 的延续问题。我现在有一个欧几里德空间中的排序坐标列表。我想以集群工作的方式对最接近的坐标进行平均,即整个集群被平均并返回欧几里得空间中的一个点。因此,例如下面的列表

a = [[ 42, 206],[ 45,  40],[ 45, 205],[ 46,  41],[ 46, 205],[ 47,  40],[ 47, 202],[ 48,  40],[ 48, 202],[ 49,  38]]

将返回 avg_coordinates = [[47.0, 39.8], [45.6, 204.0]]。这是通过平均前 5 个最近点(或簇)然后最后 5 个最近点来完成的。现在我正在使用梯度方法,我正在遍历所有坐标,只要梯度高于某个设定的阈值,我就会认为它是另一个点簇(因为列表已经排序)。但是当我在梯度公式 gradient = (y2-y1)/(x2-x1) 中有比分子更高的分母时,问题就出现了,它返回一个比阈值更小的值。所以从逻辑上讲我做错了。这样做有什么好的建议吗?请注意,我不想应用集群。

最佳答案

这是一种方法-

thresh = 100 # Threshold for splitting, heuristically chosen for given sample

# Lex-sort of coordinates
b = a[np.lexsort(a.T)]

# Interval indices that partition the clusters
diff_idx = np.flatnonzero(np.linalg.norm(b[1:] - b[:-1],axis=1) > thresh)+1
idx = np.hstack((0, diff_idx, b.shape[0]))
sums = np.add.reduceat(b, idx[:-1])
counts = idx[1:] - idx[:-1]
out = sums/counts.astype(float)[:,None]

示例输入、输出-

In [141]: a
Out[141]: 
array([[ 42, 206],
       [ 45,  40],
       [ 45, 205],
       [ 46,  41],
       [ 46, 205],
       [ 47,  40],
       [ 47, 202],
       [ 48,  40],
       [ 48, 202],
       [ 49,  38]])

In [142]: out
Out[142]: 
array([[  47. ,   39.8],
       [  45.6,  204. ]])

关于python - Python中的平均最近坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909541/

相关文章:

python - CherryPy 日志记录 : How do I configure and use the global and application level loggers?

java - 将结果集转换为字符串数组

c++ - 从 CUDA 数组中删除元素

python - Python 中的 URL 嗅探

python - crypt.crypt 引发 OSError : Invalid Argument

python - 使用 Python 列出订阅中的所有 Azure 数据工厂

ruby - 为什么我的散列具有映射到多个值的相同键?

python - 如何在Python中正确索引大矩阵

python - numpy 数组的 Cython 开销

numpy - 指定numpy的multivariate_normal随机采样中的球面协方差