Hi everyone,
This is probably a simple question, but I am trying to calculate the 2D polyfit on a 2D numpy array. However, unlike the 1D array poly fit, increasing the degrees results in a much worse result. In the 1D case, the higher the degree, the lower the error between the fit and the original data. Below is a minimal example which demonstrates this:
import numpy as np
import matplotlib.pyplot as plt
# Input data
a = np.array([[31.93374405, 32.09811459, 32.60427797, 34.02710551, 34.69049702, 34.58565112,
34.33578857, 33.9491244 ],
[31.95476843, 32.04424433, 32.06624189, 33.72400109, 34.09484176, 34.60559209,
34.3172927, 34.00842212]])
# Degree of the polynomial fit in x and y dimensions
degree_x = 2
degree_y = 2
# Generate grid points for evaluation
x = np.arange(a.shape[1])
y = np.arange(a.shape[0])
x_grid, y_grid = np.meshgrid(x, y)
# Flatten the grid points and the corresponding values
X_flat = x_grid.flatten()
Y_flat = y_grid.flatten()
Z_flat = a.flatten()
# Generate Vandermonde matrix
V = np.polynomial.polynomial.polyvander2d(X_flat, Y_flat, [degree_x, degree_y])
# Calculate polynomial coefficients using least squares
coeffs, _, _, _ = np.linalg.lstsq(V, Z_flat)
# Reshape the coefficients into a 2D matrix
coeffs_matrix = np.reshape(coeffs, (degree_y + 1, degree_x + 1))
# Evaluate the polynomial equation on the grid
poly_fit = np.polynomial.polynomial.polyval2d(x_grid, y_grid, coeffs_matrix)
# Plot the original data and the polynomial fit
plt.pcolor(x_grid, y_grid, a, cmap='viridis')
# plt.colorbar(label='Value')
plt.show()
plt.pcolor(x_grid, y_grid, poly_fit, linestyles='dashed')
plt.xlabel('x')
plt.ylabel('y')
plt.title('2D Polynomial Fit')
plt.show()
Increasing degree_x
and degree_y
leads to wildly wrong fits. I’m not sure why this is. Any help would be appreciated!