【问题标题】:scipy.spatial ValueError when trying to run kdtree尝试运行 kdtree 时出现 scipy.spatial ValueError
【发布时间】:2017-01-09 19:48:11
【问题描述】:

背景:我正在尝试使用 cKDtree 函数在一个 shapefile 上运行最近邻,该 shapefile 有 201 条带纬度/经度的记录,针对 8760 小时的时间序列数据集(总小时数年)。我得到一个错误,自然我查了一下。我发现了这个:scipy.spatial ValueError: "x must consist of vectors of length %d but has shape %s" 这是同一个错误,但我无法理解这个错误是如何解决的。

工作流程:我从 shapefile 中提取了 x 和 y 坐标,并将它们存储在名为 x_vectory_vector 的单独数组中。 8760 数据是 hdf5 文件。我使用h5_coords = np.vstack([meta['latitude'], meta['longitude']]).T 拉出坐标。

现在我尝试运行 kdtree,

# Run the kdtree to match nearest values
tree = cKDTree(np.vstack([x_vector, y_vector]))
kdtree_indices = tree.query(h5_coords)[1]

但它会导致同样的回溯错误。

回溯错误:

Traceback (most recent call last):
File "meera_extract.py", line 45, in <module>
kdtree_indices = tree.query(h5_coords)[1]
File "scipy/spatial/ckdtree.pyx", line 618, in scipy.spatial.ckdtree.cKDTree.query (scipy/spatial/ckdtree.cxx:6996)
ValueError: x must consist of vectors of length 201 but has shape (1, 389880)

帮助我,stackoverflow。你是我唯一的希望。

【问题讨论】:

  • x_vector.shapey_vector.shapeh5_coords.shape 的输出是什么?
  • 不要将np.vstack([...]) 传递给cKDTree,而是采取更小的步骤并使用points = np.vstack([x_vector, y_vector])。然后看看points.shape。是你所期望的吗?
  • x_vector.shape & y_vector.shape 是 (201,) 和 h5_coords.shape(1, 389880)
  • 啊,在这种情况下,np.vstack([x_vector, y_vector]) 的形状为 (2, 201)。这意味着您在 201 维空间中仅通过了 cKDTree 两个点。
  • 使用np.column_stack() 而不是numpy.vstack()

标签: python numpy kdtree


【解决方案1】:

所以看来我需要了解vstackcolumn_stack 的区别以及转置的使用,即.T。如果有人在这里遇到同样的问题,那么我更改为使cKDtree 工作。希望如果其他人遇到这个问题会有所帮助。非常感谢社区的 cmets 帮助解决这个问题!

我将hdf5 坐标的引入方式从vstack 更改为column_stack,并删除了转置.T

# Get coordinates of HDF5 file
h5_coords = np.column_stack([meta['latitude'], meta['longitude']])

我没有尝试在树中添加点,而是创建了一个新变量来保存它们:

# combine x and y
vector_pnts = np.column_stack([x_vector, y_vector])

然后我运行 kdtree 没有任何错误。

# Run the kdtree to match nearest values
tree = cKDTree(vector_pnts)
kdtree_indices = tree.query(h5_coords)[1]

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多