我有一个python代码,它根据x和y值计算z值。总而言之,我有7个x和7个y值以及49个z值。
现在,我想以z = f(x,y)的形式拟合2阶的多项式曲面。我找到了一个Matlab命令,可以实现这个目的。 (https://www.mathworks.com/help/curvefit/fit.html)
load franke
sf = fit([x, y],z,'poly23')
plot(sf,[x,y],z)
但是,我想用Python计算我的2度函数的参数。我尝试使用scipy curve_fit函数和以下拟合函数:
def func(a, b, c, d ,e ,f ,g ,h ,i ,j, x, y):
return a + b * x**0 * y**0 + c * x**0 * y**1 + d * x**0 * y**2
+ e * x**1 * y**0 + f * x**1 * y**1 + g * x**1 * y**2
+ h * x**2 * y**0 + i * x**2 * y**1 + j * x**2 * y**2
guess = (1,1,1,1,1,1,1,1,1,1)
params, pcov = optimize.curve_fit(func, x, y, guess)
但是在这一点上我感到困惑,我不确定,如果这是获得我的fit函数参数的正确方法。这个问题可能有另一种解决方案吗?非常感谢!
答案 0 :(得分:1)
我编写了一个Python tkinter GUI应用程序,它正是这样做的,它使用matplotlib绘制表面图,并可以将拟合结果和图形保存为PDF。代码在github上:
https://github.com/zunzun/tkInterFit/
尝试3D多项式"完全二次"因为它与您的问题中显示的方程式相同。
答案 1 :(得分:0)
现在,两年后,我能够解决问题: 这是具有多项式特征的经典回归问题,其中输入变量排列在网格中。在下面的代码中,我分别计算了所需的多项式特征,这些多项式将解释目标变量。
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# create random data, which will be the target values
Z = np.random.rand(7,7) * 100
# create a 2D-mesh
x = np.arange(1,8).reshape(7,1)
y = np.arange(1,8).reshape(1,7)
X,Y = np.meshgrid(x,y)
# calculate polynomial features based on the input mesh
features = {}
features['x^0*y^0'] = np.matmul(x**0,y**0).flatten()
features['x*y'] = np.matmul(x,y).flatten()
features['x*y^2'] = np.matmul(x,y**2).flatten()
features['x^2*y^0'] = np.matmul(x**2, y**0).flatten()
features['x^2*y'] = np.matmul(x**2, y).flatten()
features['x^3*y^2'] = np.matmul(x**3, y**2).flatten()
features['x^3*y'] = np.matmul(x**3, y).flatten()
features['x^0*y^3'] = np.matmul(x**0, y**3).flatten()
dataset = pd.DataFrame(features)
# fit a linear regression model
reg = LinearRegression().fit(dataset.values, Z.flatten())
# get coefficients and calculate the predictions
z_pred = reg.intercept_ + np.matmul(dataset.values, reg.coef_.reshape(-1,1)).reshape(7,7)
# visualize the results
fig = plt.figure(figsize = (10,10))
ax = Axes3D(fig)
# plot the fitted curve
ax.plot_wireframe(X, Y, z_pred)
# plot the target values
ax.scatter(X, Y, Z, c = 'r')
plt.show()
3D scatter plot of the target variables and the fitted curve