首页 > 解决方案 > 这是在python中拟合从高斯分布生成的数据的正确方法吗?

问题描述

我正在尝试编写一个 Python 程序来生成使用随机变量(具有高斯分布)和 4 次多项式方程(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

标签: pythonplotcurve-fittinggaussianleast-squares

解决方案


是的,你只需要尝试

model = np.polyfit(xvals, yvals, i) # i=4 to get the perfect fit to values with R-Square of 4 : 0.9999995005089268.

推荐阅读