【发布时间】:2016-11-05 15:21:14
【问题描述】:
我有一些大型数据集,我想在其中拟合单指数时间衰减。
数据由在不同时间获取的多个 4D 数据集组成,因此拟合应该沿着第 5 维(通过数据集)运行。
我目前使用的代码如下:
import numpy as np
import scipy.optimize as opt
[... load 4D datasets ....]
data = (dataset1, dataset2, dataset3)
times = (10, 20, 30)
def monoexponential(t, M0, t_const):
return M0*np.exp(-t/t_const)
# Starting guesses to initiate descent.
M0_init = 80.0
t_const_init = 50.0
init_guess = (M0_init, t_const_init)
def fit(vector):
try:
nlfit, nlpcov = opt.curve_fit(monoexponential, times, vector,
p0=init_guess,
sigma=None,
check_finite=False,
maxfev=100, ftol=0.5, xtol=1,
bounds=([0, 2000], [0, 800]))
M0, t_const = nlfit
except:
t_const = 0
return t_const
# Concatenate datasets in data into a single 5D array.
concat5D = np.concatenate([block[..., np.newaxis] for block in data],
axis=len(data[0].shape))
# And apply the curve fitting along the last dimension.
decay_map = np.apply_along_axis(fit, len(concat5D.shape) - 1, concat5D)
代码运行良好,但需要很长时间(例如,dataset1.shape == (100,100,50,500))。我读过一些其他主题提到apply_along_axis 非常慢,所以我猜这是罪魁祸首。不幸的是,我真的不知道这里可以使用什么替代方案(除了可能是显式的 for 循环?)。
有没有人知道我可以做些什么来避免apply_along_axis 并加快curve_fit 被多次调用的速度?
【问题讨论】:
标签: python performance python-2.7 numpy scipy