下面的代码将scipy的曲线拟合参数限制在指定的范围内。在本例中,第一个参数的边界为+/-无穷大(无界),第二个参数的边界为+/-100,但拟合参数在边界内并正常拟合,第三个参数受其边界限制。在import numpy
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([5.0, 6.1, 7.2, 8.3, 9.4])
yData = numpy.array([ 10.0, 18.4, 20.8, 23.2, 35.0])
def standardFunc(data, a, b, c):
return a * data + b * data**2 + c
# some initial parameter values - must be within bounds
initialParameters = numpy.array([1.0, 1.0, 1.0])
# bounds on parameters - initial parameters must be within these
lowerBounds = (-numpy.Inf, -100.0, -5.0)
upperBounds = (numpy.Inf, 100.0, 5.0)
parameterBounds = [lowerBounds, upperBounds]
fittedParameters, pcov = curve_fit(standardFunc, xData, yData, initialParameters, bounds = parameterBounds)
# values for display of fitted function
a, b, c = fittedParameters
# for plotting the fitting results
xPlotData = numpy.linspace(min(xData), max(xData), 50)
y_plot = standardFunc(xPlotData, a, b, c)
plt.plot(xData, yData, 'D') # plot the raw data as a scatterplot
plt.plot(xPlotData, y_plot) # plot the equation using the fitted parameters
plt.show()
print('fitted parameters:', fittedParameters)