Scipyinterp2d返回函数自动且不受欢迎地对输入参数排序

2024-05-23 19:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

documentation之后:

import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx+yy)
f = interpolate.interp2d(x, y, z, kind='cubic')

我继续评估f:

^{pr2}$

输出:

array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])

颠倒论点会得到同样的结果!我本以为会得到相反的结果:

xnewrev=np.array(list(reversed(np.arange(-5.01, 5.01, 1e-2))))
f(xnewrev, 0)

输出:

array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])

期望:

array([-0.96171273, -0.96171273, -0.96443103, ...,  0.96176018,
    0.9589498 ,  0.95603946])

在洗牌之后,我也得到相同的结果xnew。似乎插值函数f在求值之前对xnew排序。如何使f返回值的顺序与输入列表中给定的顺序相同?在

不知何故,这不是interp1d的问题

我使用的是Jupyter笔记本,Python2.7.12 | Anaconda 4.1.1(64位)


Tags: import顺序matplotlibdocumentationasnppltarray
2条回答

基于hpaulj's answer,可以定义一个返回未排序数组的新类,例如

from scipy.interpolate import interp2d
import numpy as np

class unsorted_interp2d(interp2d):
    def __call__(self, x, y, dx=0, dy=0):
        unsorted_idxs = np.argsort(np.argsort(x))
        return interp2d.__call__(self, x, y, dx=dx, dy=dy)[unsorted_idxs]

然后,在您的示例中,您将拥有:

^{pr2}$

您的f可调用参数采用assume_sorted参数:

assume_sorted : bool, optional
    If False, values of `x` and `y` can be in any order and they are
    sorted first.
    If True, `x` and `y` have to be arrays of monotonically
    increasing values.

所以,是的,输入是内部排序的,如果你事先没有排序的话。我看不到坐标的倒数。在

在使用之前,xy输入到interp2d也被排序。显然插值计算需要排序数组。在

可以使用双argsort索引恢复预排序顺序

制作一个数组并洗牌:

^{pr2}$

获取恢复索引:

In [419]: idx = np.argsort(np.argsort(xnew))
In [420]: idx
Out[420]: array([ 5,  6,  8,  4, 10,  3,  9,  1,  0,  2,  7], dtype=int32)

测试一下:

In [421]: np.sort(xnew)[idx]
Out[421]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])

相关问题 更多 >