Wolfgang Kerzendorf
Wolfgang Kerzendorf

Reputation: 734

polynomial surface fit numpy

How do I fit a 2D surface z=f(x,y) with a polynomial in numpy with full cross terms?

Upvotes: 1

Views: 4063

Answers (2)

Charles Harris
Charles Harris

Reputation: 1084

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.

Upvotes: 0

dwf
dwf

Reputation: 3563

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.

Upvotes: 7

Related Questions