python - Scipy-interp2d 返回的函数自动对输入参数进行排序,但不符合预期

标签 python scipy

遵循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:

xnew = np.arange(-5.01, 5.01, 1e-2)
f(xnew, 0)

输出:

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 笔记本、Python 2.7.12 |Anaconda 4.1.1(64 位)

最佳答案

您的 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.

所以,是的,如果您事先没有对输入进行排序,那么它们会在内部进行排序。我没有找到恢复排序坐标的方法。

interp2dx,y 输入在使用前也会进行排序。显然插值计算需要排序数组。

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

创建一个数组并对其进行打乱:

In [415]: xnew = np.arange(-10,11,2)
In [416]: xnew
Out[416]: array([-10,  -8,  -6,  -4,  -2,   0,   2,   4,   6,   8,  10])
In [417]: np.random.shuffle(xnew)
In [418]: xnew
Out[418]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])

获取恢复索引:

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])

关于python - Scipy-interp2d 返回的函数自动对输入参数进行排序,但不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941271/

相关文章:

Python 类继承和 __dict__ 查找

scipy - 如何使用 skewnorm 生成具有指定偏斜的分布?

numpy 数组到 scipy.sparse 矩阵

python - 从 SQL 数据库导入表并按日期过滤行时,将 Pandas 列解析为 Datetime

python - 在 Python 中使用 'nearest' 方法进行外推

python - 用 pandas 对列进行分箱

python Pandas |为每一列创建单独的列表

python - 解码 CSV 文件中的 UTF8 文字

python - 如何使用 ANN 和遗传算法在 Python 中为井字游戏创建 AI?

python - 检查点是否位于凸包内