首页 > 解决方案 > 出于神秘原因,函数为 numpy 数组定义了一个不需要的属性

问题描述

我正在尝试构建一个网格网格以计算插值。我从这个例子中得到启发。我的功能如下:

def oscillatory_(a,b,d,w=w,c=c):
    x = np.array([a,b,d])
    return np.cos(2*math.pi*w[0,0] + np.sum(c.T*x, axis = 1))

我打电话给:

data = oscillatory_(*np.meshgrid(a,b,d,indexing='ij', sparse=True))

在哪里

a = grid_dim[:,0]
b = grid_dim[:,1]
d = grid_dim[:,2]

只是从 grid_dim 获取的一些值,它是一个 numpy n-array

尝试运行代码时,出现以下错误:

    Traceback (most recent call last):
  File "/usr/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 9, in <module>
  File "<input>", line 3, in f
AttributeError: 'numpy.ndarray' object has no attribute 'cos'

我真的不明白他为什么将 cos 分配为属性而不是函数,因为如果我在 *np.meshgrid() 之外运行振荡函数,一切正常。

另外,我玩过下面链接中的玩具示例,添加了一个 np.cos 函数,一切正常。问题出在我的功能上,我不知道在哪里。

我这样做是为了通过以下方式计算插值:

my_interpolating_function = RegularGridInterpolator((a,b,d), data)

对此的任何帮助将不胜感激。非常感谢

标签: pythonnumpyinterpolation

解决方案


从稀疏创建一个数组meshgrid会产生一个对象 dtype 数组

In [448]: I,J=np.meshgrid([0,1,2],[0,1], indexing='ij', sparse=True)                 
In [449]: I                                                                          
Out[449]: 
array([[0],
       [1],
       [2]])
In [450]: J                                                                          
Out[450]: array([[0, 1]])
In [451]: np.array([I, J])                                                           
Out[451]: 
array([array([[0],
       [1],
       [2]]), array([[0, 1]])], dtype=object)

使用稀疏 False,您将获得一个有效的数值数组:

In [452]: I,J=np.meshgrid([0,1,2],[0,1], indexing='ij', sparse=False)                
In [453]: I                                                                          
Out[453]: 
array([[0, 0],
       [1, 1],
       [2, 2]])
In [454]: J                                                                          
Out[454]: 
array([[0, 1],
       [0, 1],
       [0, 1]])
In [455]: np.array([I, J])                                                           
Out[455]: 
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[0, 1],
        [0, 1],
        [0, 1]]])

推荐阅读