python - 这是在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()
解决方案
是的,你只需要尝试
model = np.polyfit(xvals, yvals, i) # i=4 to get the perfect fit to values with R-Square of 4 : 0.9999995005089268.
推荐阅读
- amazon-cognito - 使用 amplify 进行 Google 身份验证时缺少必需的参数 client_id
- react-native - 在本机反应中无法读取 null 的属性“scrollTo”
- c# - System.ServiceModel.FaultException - 如何解决这个问题
- meshlab - 网格导出无法构建可读的层文件
- python - 如何将多行的信息拆分为列?
- java - 使用时区转换导出数据
- javascript - 如何从数组中删除特定的嵌套对象?
- javascript - Error: SyntaxError: Unexpected token C in JSON at position 33 in rule attachments while doing on google firebase
- arrays - 通过指向 2D 字符数组的指针访问。警告:数组初始值设定项中的多余元素
- angular - 类型脚本错误 TS2554:预期 0 个参数,但在离子应用程序中得到 1 个