从数据集的长度来看,似乎意图是将被积函数(t)拟合到输出(t+dt)。 scipy 优化模块中有几个函数可用于执行此操作。举一个简单的例子,我们展示了一个使用 scipy.optimize.leastsqr() 的实现。有关详细信息,请参阅scipy optimize的教程
基本方案是创建一个函数,该函数在独立坐标上评估模型函数,并返回一个包含残差、模型和每个点的观察值之间的差异的 numpy 数组。 leastsq() 找到一组参数的值,使残差的平方和最小。
我们需要注意的是,拟合可能对初始猜测很敏感。
模拟退火通常用于找到可能的全局最小值,并在细化拟合之前提供拟合参数的粗略估计。此处用于初始猜测的值仅用于概念目的。
from scipy.optimize import leastsq
import numpy as np
# Read the data files
Pm = np.array( [ float(v) for v in open( "impulse_data.txt", "r" ).readlines() ] )
print type(Pm), Pm.shape
tm = np.array( [ float(v) for v in open( "Impulse_time_axis.txt", "r" ).readlines() ] )
print type(tm), tm.shape
output = np.array( [ float(v) for v in open( "Output_data.txt", "r" ).readlines() ] )
print type(output), output.shape
tout = np.array( [ float(v) for v in open( "Output_time_axis.txt", "r" ).readlines() ] )
print type(tout), tout.shape
# Define the function that calculates the residuals
def residuals( coeffs, output, tm ):
dt, alpha1, alpha2 = coeffs
res = np.zeros( tm.shape )
for n,t in enumerate(tm):
# integrate to "t"
value = sum( Pm[:n]*(1-np.e**( -(alpha1 * (tm[:n]+dt))) )*np.e**(-(alpha2 * (tm[:n]+dt))) )
# retrieve output at t+dt
n1 = (np.abs(tout - (t+dt) )).argmin()
# construct the residual
res[n] = output[n1] - value
return res
# Initial guess for the parameters
x0 = (10.,1.,1.)
# Run the least squares routine
coeffs, flag = leastsq( residuals, x0, args=(output,tm) )
# Report the results
print( coeffs )
print( flag )