Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit 3D Polynomial Surface with Python

I have a python code that calculates z values dependent on x and y values. Overall, I have 7 x-values and 7 y-values as well as 49 z-values that are arranged in a grid (x and y correspond each to one axis, z is the height).

Now, I would like to fit a polynomial surface of degree 2 in the form of z = f(x,y).

I found a Matlab command that does this calculation. (https://www.mathworks.com/help/curvefit/fit.html)

load franke
sf = fit([x, y],z,'poly23')
plot(sf,[x,y],z)

I want to calculate the parameters of my 2 degree function in Python. I tried to use the scipy curve_fit function with the following fit function:

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)

But at this point I am getting confused and I am not sure, if this is the right approach to get the parameters for my fit function. Is there possibly another solution for this problem? Thank's a lot!

like image 377
lux7 Avatar asked Dec 06 '16 11:12

lux7


People also ask

How to fit a polynomial to a 2D surface?

Example: Polynomial Surface Fit¶ In this example, we want to fit a polynomial to a 2D surface. Suppose the surface is described by \[f(x) = x^2 + y^2 + 2 x y\]

How do I fit a 3rd order polynomial in griddata?

Griddata uses a spline fitting. A 3rd order spline is not the same thing as a 3rd order polynomial (instead, it's a different 3rd order polynomial at every point). If you just want to fit a 2D, 3rd order polynomial to your data, then do something like the following to estimate the 16 coefficients using all of your data points.

How to make a polynomial fit in Matplotlib?

A fit to such data can be performed as follows: fromsymfitimportPoly,variables,parameters,Model,Fitimportnumpyasnpimportmatplotlib.pyplotaspltimportseabornassnsx,y,z=variables('x, y, z')c1,c2=parameters('c1, c2')# Make a polynomial.

How does surface fitting work?

Please see the following functions for details: Surface fitting generates control points grid defined in u and v parametric dimensions. Therefore, the input requires number of data points to be fitted in both parametric dimensions.


2 Answers

This is a linear regression problem with polynomial features, where the input variables are arranged in a mesh. In the code below, I calculated the polynomial features I need, respectively that ones, that will explain my target variable.

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 Plot of input variables and predicted surface

like image 200
lux7 Avatar answered Sep 22 '22 10:09

lux7


I wrote a Python tkinter GUI application that does exactly this, it draws the surface plot with matplotlib and can save fitting results and graphs to PDF. The code is on github at:

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

Try the 3D Polynomial "Full Quadratic" as it is the same equation shown in your question.

like image 45
James Phillips Avatar answered Sep 18 '22 10:09

James Phillips