Scipy的N维插值在使用 "sparse=True "时,会产生意外的ValueError。

问题描述 投票:1回答:1

我正在研究一个n-D插值的例子,使用的是 scipy.interpolate.interpn. 下面的玩具示例代码可以正常工作,符合预期。

#!/usr/bin/env python3
from scipy.interpolate import interpn
import numpy as np

x=np.arange(4)
y=np.arange(3)
z=np.arange(2)
xx = np.linspace(0, 3, 7)
yy = np.linspace(0,2, 5)
zz = np.linspace(0,1,3)
a1=np.arange(24)
a1=a1.reshape((4,3,2))

grids=np.array(np.meshgrid(xx,yy,zz, indexing='ij'))   
grids=np.moveaxis(grids, 0, -1)
a2=interpn((x,y,z), a1, grids)

然而,如果我改变 grids=np.array(np.meshgrid(xx,yy,zz, indexing='ij'))

    grids=np.array(np.meshgrid(xx,yy,zz, sparse=True, indexing='ij'))

我得到了 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),这表明

homezell.locallibpython3.6site-packagesscipy-1.4.1-py3.6-linux-x86_64.eggscipyinterpolateinterpolate.py(2645)interpn()

这个问题似乎是由 "sparse=True "引入的。我怎样才能在保持 "sparse=True "的同时解决这个问题(因为我的网格会占用很多内存)?

python scipy interpolation
1个回答
2
投票

meshgrid 制作3个数组,每个输入数组一个。 如果没有 sparse每一个都是一个3D数组,形状相同。

In [95]: len(np.meshgrid(xx,yy,zz, indexing='ij'))                                                              
Out[95]: 3
In [96]: np.meshgrid(xx,yy,zz, indexing='ij')[0].shape                                                          
Out[96]: (7, 5, 3)

当你把它包在 np.array 你会得到一个(3, 7, 5, 3)数组。

有了 sparse,它使3个数组,3D也是,但不全。 它们以同样的方式一起广播,但没有重复的元素。

In [97]: np.meshgrid(xx,yy,zz, indexing='ij', sparse=True)[0].shape                                             
Out[97]: (7, 1, 1)
In [98]: np.meshgrid(xx,yy,zz, indexing='ij', sparse=True)[1].shape                                             
Out[98]: (1, 5, 1)
In [99]: np.meshgrid(xx,yy,zz, indexing='ij', sparse=True)[2].shape                                             
Out[99]: (1, 1, 3)

你不能像以前那样把这些东西变成一个4d数组!

在最新的1.19dev中,我得到了这个警告。

In [101]: np.array(np.meshgrid(xx,yy,zz, indexing='ij', sparse=True)).shape                                     
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Creating an 
ndarray from ragged nested sequences (which is a list-or-tuple of 
lists-or-tuples-or ndarrays with different lengths or shapes) is 
deprecated. If you meant to do this, you must specify 'dtype=object' 
when creating the ndarray
  #!/usr/bin/python3
Out[101]: (3,)

是这个3个元素的dtype对象数组给了 interpn 问题。

interpn docs指定的 xi 争论为

 xi - ndarray of shape (…, ndim)
The coordinates to sample the gridded data at

很明显,它期望的是常规的numpy数组,而不是一个 "粗糙 "的数组。

© www.soinside.com 2019 - 2024. All rights reserved.