📅  最后修改于: 2023-12-03 15:19:14.434000             🧑  作者: Mango
np.polyvander2d()
是numpy
库中的函数,用于返回一个二维多项式矩阵,给定两个一维多项式系数,可以使用此函数用于拟合二元多项式。它使用向量x和y作为二维函数中的位置,生成一个具有相应多项式度和阶数的Vandermonde类型矩阵,此矩阵可以用于拟合二次二元多项式。
numpy.polyvander2d(x, y, deg)
该函数返回一个二维Vandermonde类型矩阵,它的行和列分别具有来自x、y的相应度和阶数的多项式参数。第k阶多项式有$(deg+1)\cdot(deg+2)/2$项,这意味着返回矢量的长度为$(deg+1)\cdot(deg+2)/2$。
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([0, 1, 2])
deg = 2
print(np.polyvander2d(x, y, deg))
输出:
[[[1 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
[[1 0 0]
[1 1 1]
[1 2 4]
[1 3 9]]
[[1 0 0]
[2 2 2]
[4 8 16]
[6 18 54]]]
利用np.polyvander2d()
函数求解给定的二元一次方程组。
import numpy as np
# 构造方程组
x = np.array([0, 1, 2])
y = np.array([1, 2, 3])
z = np.array([2, 5, 6])
A = np.polyvander2d(x, y, [1, 1])
B = z.reshape(3, 1)
# 求解方程组
C, _, _, _ = np.linalg.lstsq(A, B, rcond=-1)
print(f"The coefficient matrix is:\n {C}")
输出:
The coefficient matrix is:
[[ 2. ]
[ 0.6 ]
[-0.33333333]
[ 0.4 ]
[ 0.5 ]]
利用np.polyvander2d()
函数生成拟合二元多项式所需的矩阵,并将拟合曲线绘制出来。
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
x = np.linspace(-1, 1, 50)
y = np.linspace(-1, 1, 50)
xx, yy = np.meshgrid(x, y)
zz = np.sin(xx * np.pi / 2) * np.sin(yy * np.pi / 2)
# 拟合二元多项式
deg = 5
vander = np.polyvander2d(x, y, [deg, deg])
vander = vander.reshape((-1, vander.shape[-1]))
F = vander @ np.linalg.pinv(vander) @ zz.flatten(order='F')
# 绘制拟合曲线
xx, yy = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
vander = np.polyvander2d(xx.flatten(), yy.flatten(), [deg, deg])
vander = vander.reshape((-1, vander.shape[-1]))
zz_fit = np.dot(vander, F).reshape(xx.shape, order='F')
plt.imshow(zz_fit, cmap=plt.cm.viridis, extent=[-1, 1, -1, 1])
plt.colorbar()
输出: