在python中不使用numpy polyfi拟合二次函数

2024-04-24 22:01:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用一个二次函数来拟合一些数据,我试图在不使用numpy的polyfit函数的情况下做到这一点。在

从数学上讲,我试图跟踪这个网站https://neutrium.net/mathematics/least-squares-fitting-of-a-polynomial/,但不知怎么的,我认为我做得不对。如果有人能帮助我,那就太好了,或者你能提出另一种方法,那也会很棒。在

我目前所做的努力:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ones = np.ones(3)
A = np.array( ((0,1),(1,1),(2,1)))
xfeature = A.T[0]
squaredfeature = A.T[0] ** 2
b = np.array( (1,2,0), ndmin=2 ).T
b = b.reshape(3)

features = np.concatenate((np.vstack(ones), np.vstack(xfeature), np.vstack(squaredfeature)), axis = 1)
featuresc = features.copy()
print(features)
m_det = np.linalg.det(features)
print(m_det)
determinants = []
for i in range(3):
    featuresc.T[i] = b
    print(featuresc)
    det = np.linalg.det(featuresc)
    determinants.append(det)
    print(det)
    featuresc = features.copy()

determinants = determinants / m_det
print(determinants)
plt.scatter(A.T[0],b)
u = np.linspace(0,3,100)
plt.plot(u, u**2*determinants[2] + u*determinants[1] + determinants[0] )
p2 = np.polyfit(A.T[0],b,2)
plt.plot(u, np.polyval(p2,u), 'b--')
plt.show()

如你所见,我的曲线与nnumpy的polyfit曲线相比并不好。 plot


更新: 我检查了我的代码,删除了所有愚蠢的错误,现在它起作用了,当我试着把它调整到超过3个点时,我不知道如何超过3个点。 updated

这是新代码:

^{pr2}$

Tags: 函数importnumpyasnponespltarray
1条回答
网友
1楼 · 发布于 2024-04-24 22:01:10

而不是使用克莱默规则,实际解决系统使用最小二乘法。记住,只有当你拥有的点数等于多项式的期望阶数加1时,克莱默法则才有效。 如果你没有这一点,那么克拉默法则将不起作用,因为你正试图找到问题的精确解决方案。如果你有更多的点,这个方法是不合适的,因为我们将创建一个超定的方程组。在

为了适应更多的点,^{}将是一个更好的拟合,因为它通过计算向量x来解决Ax=b的解,该向量使用矩阵a最小化欧几里德范数。因此,从特征矩阵的最后一列中删除y值并求解系数,然后使用numpy.linalg.lstsq来求解系数:

import numpy as np
import matplotlib.pyplot as plt


ones = np.ones(4)
xfeature = np.asarray([0,1,2,3])
squaredfeature = xfeature ** 2
b = np.asarray([1,2,0,3])

features = np.concatenate((np.vstack(ones),np.vstack(xfeature),np.vstack(squaredfeature)), axis = 1) # Change - remove the y values

determinants = np.linalg.lstsq(features, b)[0] # Change - use least squares
plt.scatter(xfeature,b)
u = np.linspace(0,3,100)
plt.plot(u, u**2*determinants[2] + u*determinants[1] + determinants[0] )
plt.show()

我现在得到了这个图,它与图中的虚线曲线相匹配,也与numpy.polyfit给出的结果相匹配:

least squares fit

相关问题 更多 >