作为一个例子,这是我的用单指数衰减拟合多指数衰减的代码(虽然并不能很好地拟合,但是仍然可以作为示例):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, curve_fit
lifetimes = [1e-9, 2e-9, 4e-9, 8e-9]
amplitudes = [1000, 1000, 1000, 1000]
background = 10
t = np.arange(1024)*1e-10
y = np.zeros(len(t))
for i in range(len(lifetimes)):
y += amplitudes[i] * np.exp(-t/lifetimes[i])
y += np.random.poisson(background, len(y))
def fit_fun(t, amplitude, lifetime, background):
return amplitude * np.exp(-t/lifetime) + background
def loss_fun(params, x, y, fit_fun, c=5):
fit_y = fit_fun(x, *params)
residuals = y - fit_y
loss = np.sum(residuals**2)
return loss
p0 = [1000, 6e-9, 10]
result = minimize(loss_fun, p0, args=(t, y, fit_fun))
params_minimize = result.x
minimize_y = fit_fun(t, *params_minimize)
params_fit, _ = curve_fit(fit_fun, t, y, p0)
fit_y = fit_fun(t, *params_fit)
plt.semilogy(t, y)
plt.semilogy(t, minimize_y)
plt.semilogy(t, fit_y)
plt.ylim([1, plt.ylim()[1]])
plt.show()
Here are the resulting fits(绿色用Curve_fit拟合,橙色用最小化)。
那么,为什么使用最小化不能正常工作?
此外,我这样做的原因是我想实现除最小二乘以外的损失函数。如果无法通过这种方式,该怎么办?