Scipy 提供了一种支持自定义函数的最小二乘曲线拟合方法。这是第一个模型的示例:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
#custom fit function - first slope steeper than second slope
def two_lin(x, m1, n1, m2, n2):
return np.min([m1 * x + n1, m2 * x + n2], axis = 0)
#x/y data points
x = np.asarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.asarray([2, 4, 8, 12, 14, 18, 20, 21, 22, 23, 24])
#initial guess for a steep rising and plateau phase
start_values = [3, 0, 0, 3]
#curve fitting
fit_param, pcov = curve_fit(two_lin, x, y, p0 = start_values)
#output of slope/intercept for both parts
m1, n1, m2, n2 = fit_param
print(m1, n1, m2, n2)
#calculating sum of squared residuals as parameter for fit quality
r = y - two_lin(x, *fit_param)
print(np.sum(np.square(r)))
#point, where the parts intersect
if m1 != m2:
x_intersect = (n2 - n1) / (m1 - m2)
print(x_intersect)
else:
print("did not find two linear components")
#plot data and fit function
x_fit = np.linspace(-1, 11, 100)
plt.plot(x, y, 'o', label='data')
plt.plot(x_fit, two_lin(x_fit, *fit_param), '--', label='fit')
plt.axis([-2, 12, 0, 30])
plt.legend()
plt.show()
更多关于scipy.optimize.curve_fit can be found in the reference guide. 的信息对于多项式,numpy 提供了numpy.polyfit 和numpy.poly1d 的标准函数,但您仍然需要提供预期的次数。
残差平方和可以用来比较不同拟合函数的准确度。