- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
假设我有来自山上 3 个(已知)高度的气象站的数据。具体来说,每个站点每分钟都会记录其所在位置的温度测量值。我有两种想要执行的插值。而且我希望能够快速执行每个操作。
所以让我们设置一些数据:
import numpy as np
from scipy.interpolate import interp1d
import pandas as pd
import seaborn as sns
np.random.seed(0)
N, sigma = 1000., 5
basetemps = 70 + (np.random.randn(N) * sigma)
midtemps = 50 + (np.random.randn(N) * sigma)
toptemps = 40 + (np.random.randn(N) * sigma)
alltemps = np.array([basetemps, midtemps, toptemps]).T # note transpose!
trend = np.sin(4 / N * np.arange(N)) * 30
trend = trend[:, np.newaxis]
altitudes = np.array([500, 1500, 4000]).astype(float)
finaltemps = pd.DataFrame(alltemps + trend, columns=altitudes)
finaltemps.index.names, finaltemps.columns.names = ['Time'], ['Altitude']
finaltemps.plot()
我认为这个很简单。假设我想每次获得海拔 1,000 的温度。我可以使用内置的 scipy
插值方法:
interping_function = interp1d(altitudes, finaltemps.values)
interped_to_1000 = interping_function(1000)
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
finaltemps.plot(ax=ax, alpha=0.15)
ax.plot(interped_to_1000, label='Interped')
ax.legend(loc='best', title=finaltemps.columns.name)
这很好用。让我们看看速度:
%%timeit
res = interp1d(altitudes, finaltemps.values)(1000)
#-> 1000 loops, best of 3: 207 µs per loop
所以现在我有第二个相关的问题。假设我知道远足派对的高度是时间的函数,并且我想通过随时间线性插值我的数据来计算他们(移动)位置的温度。 特别是,我知道远足聚会地点的时间与我知道气象站温度的时间相同。我也可以做到这一点努力:
location = np.linspace(altitudes[0], altitudes[-1], N)
interped_along_path = np.array([interp1d(altitudes, finaltemps.values[i, :])(loc)
for i, loc in enumerate(location)])
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
finaltemps.plot(ax=ax, alpha=0.15)
ax.plot(interped_along_path, label='Interped')
ax.legend(loc='best', title=finaltemps.columns.name)
所以这非常有效,但重要的是要注意上面的关键行是使用列表推导来隐藏大量工作。在前面的例子中,scipy
正在为我们创建一个插值函数,并在大量数据上对其进行一次评估。在这种情况下,scipy
实际上是在构造 N
个单独的插值函数,并在少量数据上对每个插值函数进行一次评估。这感觉本质上是低效的。这里(在列表理解中)潜伏着一个 for 循环,而且,这感觉很松散。
毫不奇怪,这比前一种情况要慢得多:
%%timeit
res = np.array([interp1d(altitudes, finaltemps.values[i, :])(loc)
for i, loc in enumerate(location)])
#-> 10 loops, best of 3: 145 ms per loop
所以第二个例子的运行速度比第一个慢 1,000。 IE。与繁重的工作是“制作线性插值函数”步骤的想法一致……在第二个示例中发生了 1,000 次,但在第一个示例中仅发生了一次。
那么,问题是:有没有更好的方法来解决第二个问题?例如,有没有一种很好的方法来设置二维插值(也许可以处理这种情况哪里知道远足聚会地点的时间不是温度采样的时间)?或者有没有一种特别巧妙的方式来处理时间紧迫的事情?还是其他?
最佳答案
两个值 y1
、y2
在位置 x1
和 x2
之间关于点的线性插值xi
很简单:
yi = y1 + (y2-y1) * (xi-x1) / (x2-x1)
通过一些向量化的 Numpy 表达式,我们可以从数据集中选择相关点并应用上述函数:
I = np.searchsorted(altitudes, location)
x1 = altitudes[I-1]
x2 = altitudes[I]
time = np.arange(len(alltemps))
y1 = alltemps[time,I-1]
y2 = alltemps[time,I]
xI = location
yI = y1 + (y2-y1) * (xI-x1) / (x2-x1)
问题是有些点位于已知范围的边界(甚至之外),应该考虑到这一点:
I = np.searchsorted(altitudes, location)
same = (location == altitudes.take(I, mode='clip'))
out_of_range = ~same & ((I == 0) | (I == altitudes.size))
I[out_of_range] = 1 # Prevent index-errors
x1 = altitudes[I-1]
x2 = altitudes[I]
time = np.arange(len(alltemps))
y1 = alltemps[time,I-1]
y2 = alltemps[time,I]
xI = location
yI = y1 + (y2-y1) * (xI-x1) / (x2-x1)
yI[out_of_range] = np.nan
幸运的是,Scipy 已经提供了 ND 插值,这也很容易处理不匹配时间,例如:
from scipy.interpolate import interpn
time = np.arange(len(alltemps))
M = 150
hiketime = np.linspace(time[0], time[-1], M)
location = np.linspace(altitudes[0], altitudes[-1], M)
xI = np.column_stack((hiketime, location))
yI = interpn((time, altitudes), alltemps, xI)
这是一个基准代码(实际上没有任何 pandas
,我确实包含了另一个答案中的解决方案):
import numpy as np
from scipy.interpolate import interp1d, interpn
def original():
return np.array([interp1d(altitudes, alltemps[i, :])(loc)
for i, loc in enumerate(location)])
def OP_self_answer():
return np.diagonal(interp1d(altitudes, alltemps)(location))
def interp_checked():
I = np.searchsorted(altitudes, location)
same = (location == altitudes.take(I, mode='clip'))
out_of_range = ~same & ((I == 0) | (I == altitudes.size))
I[out_of_range] = 1 # Prevent index-errors
x1 = altitudes[I-1]
x2 = altitudes[I]
time = np.arange(len(alltemps))
y1 = alltemps[time,I-1]
y2 = alltemps[time,I]
xI = location
yI = y1 + (y2-y1) * (xI-x1) / (x2-x1)
yI[out_of_range] = np.nan
return yI
def scipy_interpn():
time = np.arange(len(alltemps))
xI = np.column_stack((time, location))
yI = interpn((time, altitudes), alltemps, xI)
return yI
N, sigma = 1000., 5
basetemps = 70 + (np.random.randn(N) * sigma)
midtemps = 50 + (np.random.randn(N) * sigma)
toptemps = 40 + (np.random.randn(N) * sigma)
trend = np.sin(4 / N * np.arange(N)) * 30
trend = trend[:, np.newaxis]
alltemps = np.array([basetemps, midtemps, toptemps]).T + trend
altitudes = np.array([500, 1500, 4000], dtype=float)
location = np.linspace(altitudes[0], altitudes[-1], N)
funcs = [original, interp_checked, scipy_interpn]
for func in funcs:
print(func.func_name)
%timeit func()
from itertools import combinations
outs = [func() for func in funcs]
print('Output allclose:')
print([np.allclose(out1, out2) for out1, out2 in combinations(outs, 2)])
在我的系统上出现以下结果:
original
10 loops, best of 3: 184 ms per loop
OP_self_answer
10 loops, best of 3: 89.3 ms per loop
interp_checked
1000 loops, best of 3: 224 µs per loop
scipy_interpn
1000 loops, best of 3: 1.36 ms per loop
Output allclose:
[True, True, True, True, True, True]
Scipy 的 interpn
与最快的方法相比在速度方面有所下降,但由于它的通用性和易用性,它绝对是要走的路。
关于python - Numpy/Scipy "along a path"中的快速线性插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33069366/
我在使用 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
我是一名优秀的程序员,十分优秀!