Python 中二维多项式的“polyfit"等价物 [英] Equivalent of `polyfit` for a 2D polynomial in Python

查看:34
本文介绍了Python 中二维多项式的“polyfit"等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为

z = (a0 + a1*x + a2*y + a3*x**2 + a4*x**2*y + a5*x**2*y**2 + a6*y**2 +
     a7*x*y**2 + a8*x*y)

给定长度为 20 的数组 xyz.基本上我正在寻找等效的 numpy.polyfit 但对于二维多项式.

given arrays x, y, and z of length 20. Basically I'm looking for the equivalent of numpy.polyfit but for a 2D polynomial.

这个问题类似,但解决方案是通过MATLAB提供的.

This question is similar, but the solution is provided via MATLAB.

推荐答案

以下示例展示了如何使用 numpy.linalg.lstsq 完成此任务:

Here is an example showing how you can use numpy.linalg.lstsq for this task:

import numpy as np

x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 20)
X, Y = np.meshgrid(x, y, copy=False)
Z = X**2 + Y**2 + np.random.rand(*X.shape)*0.01

X = X.flatten()
Y = Y.flatten()

A = np.array([X*0+1, X, Y, X**2, X**2*Y, X**2*Y**2, Y**2, X*Y**2, X*Y]).T
B = Z.flatten()

coeff, r, rank, s = np.linalg.lstsq(A, B)

调整系数coeff为:

array([ 0.00423365,  0.00224748,  0.00193344,  0.9982576 , -0.00594063,
        0.00834339,  0.99803901, -0.00536561,  0.00286598])

注意coeff[3]coeff[6]分别对应X**2Y**2,它们接近 1. 因为示例数据是用 Z = X**2 + Y**2 + small_random_component 创建的.

Note that coeff[3] and coeff[6] respectively correspond to X**2 and Y**2, and they are close to 1. because the example data was created with Z = X**2 + Y**2 + small_random_component.

这篇关于Python 中二维多项式的“polyfit"等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆