- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 scipy.interpolate.RegularGridInterpolator
和 method='linear'
。获取内插值很简单(参见 https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.interpolate.RegularGridInterpolator.html 中的示例)。获取梯度和插值的好方法是什么?
一种可能性是多次调用插值器并使用有限差分“手动”计算梯度。鉴于对插值器的每次调用可能已经在后台计算梯度,这感觉很浪费。那是对的吗?如果是这样,我如何修改 RegularGridInterpolator 以返回插值函数值及其梯度?
明确地说,我对我插值的函数的“真实”梯度不感兴趣——只是线性近似的梯度,例如https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.interpolate.RegularGridInterpolator.html 示例中 my_interpolating_function
的梯度.
这是一个例子。我有一个函数 f
,我构建了一个线性插值器 f_interp
,我对 f_interp
的梯度感兴趣(与f
)。我可以使用有限差分来计算它,但是有更好的方法吗?我假设 RegularGridInterpolator
已经在后台计算梯度——而且速度很快。我如何修改它以返回梯度以及插值?
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as interp
def f(x, y, z):
return 0.01*x**2 + 0.05*x**3 + 5*x*y + 3*x*y*z + 0.1*x*(y**2)*z + 9*x*z**2 - 2*y
x_grid = np.linspace(0.0, 10.0, 20)
y_grid = np.linspace(-10.0, 10.0, 20)
z_grid = np.linspace(0.0, 20.0, 20)
mesh = np.meshgrid(x_grid, y_grid, z_grid, indexing="ij")
f_on_grid = f(mesh[0], mesh[1], mesh[2])
assert np.isclose(f_on_grid[0, 0, 0], f(x_grid[0], y_grid[0], z_grid[0])) # Sanity check
grid = (x_grid, y_grid, z_grid)
f_interp = interp.RegularGridInterpolator(grid, f_on_grid, method="linear",
bounds_error=False, fill_value=None)
dense_x = np.linspace(0.0, 20.0, 400)
plt.plot(dense_x, [f_interp([x, 1.0, 2.0])[0] for x in dense_x], label="y=1.0, z=2.0")
plt.plot(dense_x, [f_interp([x, 1.0, 4.0])[0] for x in dense_x], label="y=1.0, z=4.0")
plt.legend()
plt.show()
f_interp([0.05, 1.0, 2.0]) # Linearly interpolated value, distinct from f(0.05, 1.0, 2.0)
## Suppose I want to compute both f_interp and its gradient at point_of_interest
point_of_interest = np.array([0.23, 1.67, 5.88])
f_interp(point_of_interest) # Function value -- how can I get f_interp to also return gradient?
## First gradient calculation using np.gradient and a mesh around point_of_interest +- delta
delta = 0.10
delta_mesh = np.meshgrid(*([-delta, 0.0, delta], ) * 3, indexing="ij")
delta_mesh_long = np.column_stack((delta_mesh[0].flatten(),
delta_mesh[1].flatten(),
delta_mesh[2].flatten()))
assert delta_mesh_long.shape[1] == 3
point_plus_delta_mesh = delta_mesh_long + point_of_interest.reshape((1, 3))
values_for_gradient = f_interp(point_plus_delta_mesh).reshape(delta_mesh[0].shape)
gradient = [x[1, 1, 1] for x in np.gradient(values_for_gradient, delta)]
gradient # Roughly [353.1, 3.8, 25.2]
## Second gradient calculation using finite differences, should give similar result
gradient = np.zeros((3, ))
for idx in [0, 1, 2]:
point_right = np.copy(point_of_interest)
point_right[idx] += delta
point_left = np.copy(point_of_interest)
point_left[idx] -= delta
gradient[idx] = (f_interp(point_right)[0] - f_interp(point_left)[0]) / (2*delta)
gradient # Roughly [353.1, 3.8, 25.2]
这是 f 和 f_interp 的图片。我对 f_interp(实线)的梯度感兴趣:
最佳答案
没有。
下面是 scipy.interpolate.RegularGridInterpolator
在幕后所做的事情:
class CartesianGrid(object):
"""
Linear Multivariate Cartesian Grid interpolation in arbitrary dimensions
This is a regular grid with equal spacing.
"""
def __init__(self, limits, values):
self.values = values
self.limits = limits
def __call__(self, *coords):
# transform coords into pixel values
coords = numpy.asarray(coords)
coords = [(c - lo) * (n - 1) / (hi - lo) for (lo, hi), c, n in zip(self.limits, coords, self.values.shape)]
return scipy.ndimage.map_coordinates(self.values, coords,
cval=numpy.nan, order=1)
https://github.com/JohannesBuchner/regulargrid/blob/master/regulargrid/cartesiangrid.py
它使用 scipy.ndimage.map_coordinates
进行线性插值。coords
包含像素坐标中的位置。您应该能够使用这些权重以及每个维度的下限值和上限值来计算插值上升的陡峭程度。
但是,梯度还取决于角点的值。
你可以在这里找到数学:https://en.wikipedia.org/wiki/Trilinear_interpolation
关于python - scipy 的 RegularGridInterpolator 能否通过一次调用同时返回值和梯度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056031/
我在使用 cx_freeze 和 scipy 时无法编译 exe。特别是,我的脚本使用 from scipy.interpolate import griddata 构建过程似乎成功完成,但是当我尝试
是否可以通过函数在 scipy 中定义一个稀疏矩阵,而不是列出所有可能的值?在文档中,我看到可以通过以下方式创建稀疏矩阵 There are seven available sparse matrix
SciPy为非线性最小二乘问题提供了两种功能: optimize.leastsq()仅使用Levenberg-Marquardt算法。 optimize.least_squares()允许我们选择Le
SciPy 中的求解器能否处理复数值(即 x=x'+i*x")?我对使用 Nelder-Mead 类型的最小化函数特别感兴趣。我通常是 Matlab 用户,我知道 Matlab 没有复杂的求解器。如果
我有看起来像这样的数据集: position number_of_tag_at_this_position 3 4 8 6 13 25 23 12 我想对这个数据集应用三次样条插值来插值标签密度;为此
所以,我正在处理维基百科转储,以计算大约 5,700,000 个页面的页面排名。这些文件经过预处理,因此不是 XML 格式。 它们取自 http://haselgrove.id.au/wikipedi
Scipy 和 Numpy 返回归一化的特征向量。我正在尝试将这些向量用于物理应用程序,我需要它们不被标准化。 例如a = np.matrix('-3, 2; -1, 0') W,V = spl.ei
基于此处提供的解释 1 ,我正在尝试使用相同的想法来加速以下积分: import scipy.integrate as si from scipy.optimize import root, fsol
这很容易重新创建。 如果我的脚本 foo.py 是: import scipy 然后运行: python pyinstaller.py --onefile foo.py 当我启动 foo.exe 时,
我想在我的代码中使用 scipy.spatial.distance.cosine。如果我执行类似 import scipy.spatial 或 from scipy import spatial 的操
Numpy 有一个基本的 pxd,声明它的 c 接口(interface)到 cython。是否有用于 scipy 组件(尤其是 scipy.integrate.quadpack)的 pxd? 或者,
有人可以帮我处理 scipy.stats.chisquare 吗?我没有统计/数学背景,我正在使用来自 https://en.wikipedia.org/wiki/Chi-squared_test 的
我正在使用 scipy.odr 拟合数据与权重,但我不知道如何获得拟合优度或 R 平方的度量。有没有人对如何使用函数存储的输出获得此度量有建议? 最佳答案 res_var Output 的属性是所谓的
我刚刚下载了新的 python 3.8,我正在尝试使用以下方法安装 scipy 包: pip3.8 install scipy 但是构建失败并出现以下错误: **Failed to build sci
我有 my own triangulation algorithm它基于 Delaunay 条件和梯度创建三角剖分,使三角形与梯度对齐。 这是一个示例输出: 以上描述与问题无关,但对于上下文是必要的。
这是一个非常基本的问题,但我似乎找不到好的答案。 scipy 到底计算什么内容 scipy.stats.norm(50,10).pdf(45) 据我了解,平均值为 50、标准差为 10 的高斯中像 4
我正在使用 curve_fit 来拟合一阶动态系统的阶跃响应,以估计增益和时间常数。我使用两种方法。第一种方法是在时域中拟合从函数生成的曲线。 # define the first order dyn
让我们假设 x ~ Poisson(2.5);我想计算类似 E(x | x > 2) 的东西。 我认为这可以通过 .dist.expect 运算符来完成,即: D = stats.poisson(2.
我正在通过 OpenMDAO 使用 SLSQP 来解决优化问题。优化工作充分;最后的 SLSQP 输出如下: Optimization terminated successfully. (Exi
log( VA ) = gamma - (1/eta)log[alpha L ^(-eta) + 测试版 K ^(-eta)] 我试图用非线性最小二乘法估计上述函数。我为此使用了 3 个不同的包(Sc
我是一名优秀的程序员,十分优秀!