polynomial surface fit numpy
How do I fit a 2D surface z=f(x,y)
with a polynomial 开发者_如何学Pythonin numpy with full cross terms?
This is inherently numerically ill-conditioned but you could do something like this:
import numpy as np
x = np.random.randn(500)
y = np.random.randn(500)
z = np.random.randn(500) # Dependent variable
v = np.array([np.ones(500), x, y, x**2, x * y, y**2])
coefficients, residues, rank, singval = np.linalg.lstsq(v.T, z)
The more terms you add, the worse things get, numerically. Are you sure you want a polynomial interpolant?
There are other bases for polynomials for which the matrix of values is not so badly conditioned but I can't remember what they are called; any college-level numerical analysis textbook would have this material, though.
You can use a combination of polyvander2d
and polyval2d
, but will need to do the fit yourself using the design matrix output from polyvander2d
, probably involving scaling and such. It should be possible to build a class Polynomial2d
from those tools.
精彩评论