使用Python拟合3D多项式曲面

问题描述 投票:2回答:2

我有一个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函数与以下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函数参数的正确方法。这个问题可能还有其他解决方案吗?非常感谢!

python 3d curve-fitting polynomials
2个回答
1
投票

我编写了一个Python tkinter GUI应用程序来完成此任务,它使用matplotlib绘制表面图,并将拟合结果和图形保存为PDF。代码在github上的位置:

https://github.com/zunzun/tkInterFit/

尝试使用3D多项式“完全二次”,因为它与您的问题中所示的方程相同。


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

np.random.seed(0)
# set dimension of the data
dim = 12
# create random data, which will be the target values
Z = (np.ones((dim,dim)) * np.arange(1,dim+1,1))**3 + np.random.rand(dim,dim) * 200 

# create a 2D-mesh
x = np.arange(1,dim+1).reshape(dim,1)
y = np.arange(1,dim+1).reshape(1,dim)
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(dim,dim)

# visualize the results
fig = plt.figure(figsize = (5,5))
ax = Axes3D(fig)
# plot the fitted curve
ax.plot_wireframe(X, Y, z_pred, label = 'prediction')
# plot the target values
ax.scatter(X, Y, Z, c = 'r', label = 'datapoints')
ax.view_init(25, 80)
plt.legend()

“输入变量和预测表面的3D图”“>

© www.soinside.com 2019 - 2024. All rights reserved.