import numpy, scipy, scipy.optimize
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # to colormap 3D surfaces from blue to red
import matplotlib.pyplot as plt
graphWidth = 800 # units are pixels
graphHeight = 600 # units are pixels
# 3D contour plot lines
numberOfContourLines = 16
def SurfacePlot(func, data, fittedParameters):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
matplotlib.pyplot.grid(True)
axes = Axes3D(f)
x_data = data[0]
y_data = data[1]
z_data = data[2]
xModel = numpy.linspace(min(x_data), max(x_data), 20)
yModel = numpy.linspace(min(y_data), max(y_data), 20)
X, Y = numpy.meshgrid(xModel, yModel)
Z = func(numpy.array([X, Y]), *fittedParameters)
axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True)
axes.scatter(x_data, y_data, z_data) # show data along with plotted surface
axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
axes.set_zlabel('Z Data') # Z axis data label
plt.show()
plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
def ContourPlot(func, data, fittedParameters):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)
x_data = data[0]
y_data = data[1]
z_data = data[2]
xModel = numpy.linspace(min(x_data), max(x_data), 20)
yModel = numpy.linspace(min(y_data), max(y_data), 20)
X, Y = numpy.meshgrid(xModel, yModel)
Z = func(numpy.array([X, Y]), *fittedParameters)
axes.plot(x_data, y_data, 'o')
axes.set_title('Contour Plot') # add a title for contour plot
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')
matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours
plt.show()
plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
def ScatterPlot(data):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
matplotlib.pyplot.grid(True)
axes = Axes3D(f)
x_data = data[0]
y_data = data[1]
z_data = data[2]
axes.scatter(x_data, y_data, z_data)
axes.set_title('Scatter Plot (click-drag with mouse)')
axes.set_xlabel('X Data')
axes.set_ylabel('Y Data')
axes.set_zlabel('Z Data')
plt.show()
plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
def func(data, a, b, c):
# extract the individual data arrays used in the equation
x = data[0]
y = data[1]
return a*x + b*y + c
def constrainedFunction(data, a, b, c):
# use a "brick wall" to ensure parameter c is positive
# return a large value and therefor large error
if c <= 0.0:
return 1.0E10
else:
return func(data, a, b, c) # call the unconstrained function
if __name__ == "__main__":
xData = numpy.array([-10.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
yData = numpy.array([-10.0, 11.0, 12.1, 13.0, 14.1, 15.0, 16.1, 17.0, 18.1, 19.0])
zData = numpy.array([-30.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.0, 9.9])
data = [xData, yData, zData]
initialParameters = [1.0, 1.0, 1.0] # these are the same as scipy default values in this example
# here a non-linear surface fit is made with scipy's curve_fit()
fittedParameters, pcov = scipy.optimize.curve_fit(constrainedFunction, [xData, yData], zData, p0 = initialParameters)
ScatterPlot(data)
SurfacePlot(func, data, fittedParameters)
ContourPlot(func, data, fittedParameters)
print('fitted prameters', fittedParameters)
3条答案
按热度按时间xcitsw881#
下面是一个图形拟合器,在拟合函数中有一个“砖墙”,它强制拟合的参数之一为正。请注意,在这个例子中,拟合非常差-如果您删除“砖墙”,则示例拟合将大大提高。这个例子使用默认的scipy curve_fit()所有1.0的初始参数估计值,并且不使用scipy的遗传算法来帮助找到初始参数估计。当使用这种技术时,初始参数估计必须在“砖墙”之外。条件,以便非线性拟合器可以正常开始。
qcbq4gxm2#
根据关于约束多元回归的注解,这里是一个图形化的3D曲面拟合器,它也有一个“砖墙”来强制拟合参数之一为正。可以使用约束或无约束函数版本调用curve_fit以进行比较。
31moq8wy3#
在Scipy“curve_fit”曲线拟合函数中,您可以为每个系数指定值的范围。传递给“curve_fit”的关键字参数“bounds”允许使用元组为每个系数指定范围。例如,如果您将二次函数传递给“curve_fit”,如a * x**2 + b * x,并且您希望0〈“a”〈2和1〈“b”〈4。你应该传递给“curve_fit”关键字参数bounds=([0,1],[2.,4.])。
“params”应该给予一个设定范围内的系数“a”和“B”列表。
文档链接:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html
https://github.com/scipy/scipy/blob/v1.10.1/scipy/optimize/_minpack_py.py#L549-L912