我有两个数组-x
和y
-对应于笛卡尔平面中的坐标(x,y)
。例如,使用scatter
中的plt.scatter(x,y)
函数(matplotlib
)(到目前为止,我正在尝试使用Python解决我的问题),我得到以下结果:{{3} }
我真正需要的是从此数据中获取隐式函数f(x,y)
,或者至少从近似函数f(x,y)
中获取系数。到目前为止,我尝试按照建议的使用curve_fit
function from scipy.optimize
,但是出现了以下错误消息:
OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
到目前为止,这是我的代码:
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy as sy
import pylab as plb
def func(x, a, b, c):
return a*x**b + c
def main():
file = open('firstcurve.out')
lines = file.read().split('\n')
file.close()
x = []
y = []
for item in lines:
if len(item) > 0:
numbers = item.split(",")
x = x + [float(numbers[0])]
y = y + [float(numbers[1])]
p0 = sy.array([1,1,1])
coeffs, matcov = curve_fit(func, x, y, p0)
yaj = func(x, coeffs[0], coeffs[1], coeffs[2])
plt.plot(x,yaj,'r-')
plt.show()
main()
任何帮助或建议都非常感谢!
PS:我正在尝试使用Python进行此操作,但是如果有任何工具可以满足我的需要,那么MatLab也可以作为一种选择。我尝试使用here,但效果不佳。
答案 0 :(得分:1)
这是用于拟合表面方程“ z = f(x,y)”的代码,绘制原始数据3D散点图,绘制3D拟合表面,并绘制等高线图。这至少应该为您提供所需的图形。
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, alpha, beta):
t = data[0]
p_p = data[1]
return a * (t**alpha) * (p_p**beta)
if __name__ == "__main__":
xData = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
yData = numpy.array([11.0, 12.1, 13.0, 14.1, 15.0, 16.1, 17.0, 18.1, 90.0])
zData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.0, 9.9])
data = [xData, yData, zData]
# this example uses curve_fit()'s default initial paramter values
fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData)
ScatterPlot(data)
SurfacePlot(func, data, fittedParameters)
ContourPlot(func, data, fittedParameters)
print('fitted prameters', fittedParameters)
答案 1 :(得分:0)
这比编码问题更多的是数学问题。您不能在python中使用曲线拟合函数,因为它正在寻找函数,即对于同一X,您不能有两个单独的Y。
如果可能的话,您可以尝试的一件事就是定义一个参数函数
x = f(t)
y = g(t)
并使用曲线拟合函数拟合x和y与t的关系。如果以这种方式表示,则可以使用平滑样条线进行拟合。
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html