要使用scipy中的最小二乘法函数,可以按照以下步骤进行操作:
- 导入必要的库和函数:
import numpy as np
from scipy.optimize import least_squares
- 定义最小二乘法的目标函数:
def fun(x, t, y):
return x[0] * np.exp(-x[1] * t) - y
这里的目标函数可以根据具体情况进行修改,这里假设目标函数为x[0] * exp(-x[1] * t) - y
。
- 准备输入数据:
t = np.array([0.1, 0.2, 0.4, 0.6, 0.9, 1.3, 1.5, 1.7, 2.0, 2.2])
y = np.array([3.2, 2.8, 2.1, 1.8, 1.0, 0.5, 0.2, 0.1, -0.1, -0.2])
- 设置初始参数估计值:
x0 = np.array([1.0, 0.1])
- 使用
least_squares
函数进行最小二乘法拟合:
res = least_squares(fun, x0, args=(t, y))
这里的fun
是目标函数,x0
是初始参数估计值,args
是额外的参数传递给目标函数。
- 查看拟合结果:
print(res.x)
这里的res.x
是最小二乘法拟合得到的参数值。
完整的代码示例如下:
import numpy as np
from scipy.optimize import least_squares
def fun(x, t, y):
return x[0] * np.exp(-x[1] * t) - y
t = np.array([0.1, 0.2, 0.4, 0.6, 0.9, 1.3, 1.5, 1.7, 2.0, 2.2])
y = np.array([3.2, 2.8, 2.1, 1.8, 1.0, 0.5, 0.2, 0.1, -0.1, -0.2])
x0 = np.array([1.0, 0.1])
res = least_squares(fun, x0, args=(t, y))
print(res.x)
运行以上代码,即可得到最小二乘法拟合得到的参数值。