这是拟合从python中的高斯分布生成的数据的正确方法吗?

问题描述 投票:1回答:1

我正在尝试编写一个Python程序来生成使用随机变量(具有高斯分布)和四次多项式方程(3x ^ 4 + x ^ 3 + 3x ^ 2 + 4x + 5)。使用最小二乘多项式拟合,使用模型弯曲生成的数据,直到您的模型可以准确预测所有值为止。我是python的新手,真的想赶上我快节奏的课程。任何帮助和进一步的解释将不胜感激。我没有for循环就尝试了它,它给出了两条曲线,但我认为它应该与初始点匹配。请参见下面的代码:

import random
import matplotlib.pyplot as plt
import numpy as np

def rSquared(obs, predicted):
    error = ((predicted - obs)**2).sum()
    mean = error/len(obs)
    return 1 - (mean/np.var(obs))

def generateData(a, b, c, d, e, xvals):
    for x in xvals:
        calcVal= a*x**4 + b*x**3 + c*x**2 + d*x + e
        yvals.append(calcVal+ random.gauss(0, 35))
xvals = np.arange(-10, 11, 1)
yvals= []
a, b, c, d, e = 3, 1, 3, 4, 5
generateData(a, b, c, d, e, xvals)
for i in range (5):
    model= np.polyfit(xvals, yvals, i)
    estYvals = np.polyval(model, xvals) 
print('R-Squared:', rSquared(yvals, estYvals))
plt.plot(xvals, yvals, 'r', label = 'Actual values') 

plt.plot(xvals, estYvals, 'bo', label = 'Predicted values')
plt.xlabel('Variable x values')
plt.ylabel('Calculated Value of Polynomial')
plt.legend()
plt.show()

此程序运行的结果在此图像myplot1中没有for循环,这就是我得到的myPlot2

python plot curve-fitting gaussian least-squares
1个回答
0
投票

[是,您只需要尝试使用model = np.polyfit(xvals,yvals,i)#i = 4即可完美拟合R平方为4的值:0.9999995005089268。

© www.soinside.com 2019 - 2024. All rights reserved.