99.3k views
2 votes
Write a Python program to generate data that uses the sum of a random variable (which has a Gaussian distribution) and a 4th-degree polynomial equation (3x4+x3+3x2+4x+5). Using least-squares polynomial fit, curve the generated data using a model until your model can accurately predict all values

2 Answers

1 vote

Answer:

Check the explanation

Step-by-step explanation:

Consider a data array x and y be the sum of the random variable(with gaussian distribution) and the 4th degree polynomial.

We shall fit the data arrays X and Y to the 4th degree polynomial.

import random

import numpy as np

import matplotlib.pyploy as plt

poly_coeff=[3,1,3,4,5]

poly=np.poly1d(poly_coeff)

y=poly(random.randint(0,10))+ min(10, max(0, random.gauss(2, 3)))

x=np.arange(-10,10)

curvefit=np.polyfit(x,y,4)

y_new=np.polyfit(curvefit,x)

plt.plot(x,y, ‘-or’)

plt.plot(x,y_new, ‘-b’)

plt.show()

User Frankie Drake
by
4.6k points
5 votes

Answer:

See explaination

Step-by-step explanation:

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()

User Kenosis
by
5.0k points