gpt4 book ai didi

python - Scipy 对结构化二维数据进行插值,但在非结构化点进行评估?

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:40 26 4
gpt4 key购买 nike

我有以下最小代码,使用 scipy.interpolate.interp2d 来对二维网格数据进行插值。

import numpy as np
from scipy import interpolate
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**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')

现在这里的f可以用来评估其他点。问题是我想要评估的点是完全随机的点,不形成规则的网格。

# Evaluate at point (x_new, y_new), in total 256*256 points
x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
func(x_new, y_new)

这会导致我的电脑出现运行时错误,它似乎将x_new和y_new视为网格,生成评估矩阵65536x65536,这不是我的目的。

运行时错误:无法生成大小为 65536x65536 的输出(大小太大)

完成任务的一种方法是使用代码逐一评估点:

z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

但是,它!!!

%timeit z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

每次循环 1.26 s ± 46.3 ms(7 次运行的平均值 ± 标准差,每次 1 次循环)

Is there any faster way to evaluate random points?

这里更快我的意思是与下面的时间相当:

x_new = np.random.random(256)
y_new = np.random.random(256)

%timeit f(x_new, y_new)

同样的 256*256 = 65536 次评估,在我的电脑上进行此操作的时间:

每次循环 1.21 ms ± 39.6 µs(7 次运行的平均值 ± 标准差,每次 1000 次循环)

它的速度不必与 1.21ms 相当,121ms 是完全可以接受的。

最佳答案

您正在寻找的函数是scipy.interpolate.RegularGridInterpolator

给定一组点 (x,y,z),其中 x 和 y 在规则网格上定义,它允许您对中间 (x,y) 点的 z 值进行采样。在您的情况下,这将如下所示

import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)

def f(x,y):
return np.sin(x**2+y**2)

z = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
func = interpolate.RegularGridInterpolator((x,y), z)

x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
xy_new = list(zip(x_new,y_new))
z_new = func(xy_new)func(xy_new)

更多详情,请参阅 https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RegularGridInterpolator.html

关于python - Scipy 对结构化二维数据进行插值,但在非结构化点进行评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086971/

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