gpt4 book ai didi

python - 了解 scipy.interpolate 的 interpn 函数

转载 作者:行者123 更新时间:2023-12-01 00:18:31 24 4
gpt4 key购买 nike

我试图理解函数scipy.interpolate的工作原理。我创建了一个小设置,但它给出了错误。这是我所做的:

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10)
gx, gy = np.meshgrid(x,y)
v = np.ones((10,10))


sample_at = np.random.random((10,10))

interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)


print(interpolated.shape)

这会产生错误:

    Traceback (most recent call last):
File "test.py", line 13, in <module>
interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)
File "/home/lib/python3.5/site-packages/scipy/interpolate/interpolate.py", line 2624, in interpn
"1-dimensional" % i)
ValueError: The points in dimension 0 must be 1-dimensional

这里发生了什么?

最佳答案

您对 interpn 请求的网格结构做出了错误的假设

ValueError: The points in dimension 0 must be 1-dimensional

这条消息有点晦涩,它引用了网格的元素,并告诉您它们必须是一维的,或者换句话说,您必须调用 interpn 而不是 (gx , gy) 作为第一个参数,但使用 (x, y)

scipy.interpolate.interpn((x, y), v, sample_at)

但是您的代码中还有另一个错误的假设,因为如果您使用上面的调用以及 sample_at 的定义,您将收到不同的错误

ValueError: The requested sample points xi have dimension 10, but this RegularGridInterpolator has dimension 2

希望有一个更清晰的含义:如果您的网格有两个维度(xy,即),则 interpn 上的所有点> 必须插值也必须是二维的...换句话说,在您的示例中,网格的 LAST 维度必须是 2

将它们放在一起(在本例中,我将使用 5 行 x 3 列的二维点的位置矩阵 sample_at)我们有

In [69]: import numpy as np 
...: import scipy.interpolate
...: import matplotlib.pyplot as plt
...:
...: x = np.arange(10)
...: y = np.arange(10)
...: v = np.ones((10,10))
...: sample_at = 8*np.random.random((30)).reshape(5, 3, 2)
...:
...: scipy.interpolate.interpn((x, y), v, sample_at)
Out[69]:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

PS:阅读源码1,里面的注释比错误信息好多了...


(1) 对我来说,源代码位于

~/lib/miniconda3/lib/python3.7/site-packages/scipy/interpolate/interpolate.py

关于python - 了解 scipy.interpolate 的 interpn 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com