In: Computer Science
Write PYTHON CODE to answer the following question:
Consider the following data:
x = [0, 2, 4, 6, 9, 11, 12, 15, 17, 19]
y = [5, 6, 7, 6, 9, 8, 8, 10, 12, 12]
Using Python, use least-squares regression to fit a straight line to the given data. Along with the slope and intercept, compute the standard error of the estimate and the correlation coefficient.
Best fit equation y = ___ + ___ x
Standard error, Sy/x = ___
Correlation coefficient, r = ___
ANSWER:
I have provided the properly commented
and indented code so you can easily copy the code as well as check
for correct indentation.
I have provided the output image of the code so you can easily
cross-check for the correct output of the code.
Have a nice and healthy day!!
CODE
# Using scipy.optimize.curve_fit for least-squares fit to straight line
# importing module
from scipy.optimize import curve_fit
# import numpy
import numpy as np
# defining data points
x = np.array([0, 2, 4, 6, 9, 11, 12, 15, 17, 19])
y = np.array([5, 6, 7, 6, 9, 8, 8, 10, 12, 12])
# defining straight line eqn function with data points x, m=slope, c = intercept
# Straight line eqn => y = mx + c
f = lambda x,m,c: m*x + c
# using curve_fit function to least-squares fit on defined straight line function
poptimized, pcov = curve_fit(f,x,y)
# fetching slope(m) and intercept from optimized parameters
m,c = poptimized
# displaying best fit eqn
print("Best fit equation y = {:.3f} + {:.3f}(x)".format(m,c))
# calculating error
# predicting y from coefficents
y_pred = f(x,m,c)
# calculating standard error between y and y_pred
# standard error = mean of absolute(y-y_pred)
std_err = np.abs(y-y_pred).mean()
# displaying result
print("Standard error, Sy/x = {:.3f}".format(std_err))
# Correlation coefficient, using corrcoef method numpy to find the same
r = np.corrcoef(y,y_pred)
# displaying result
print("Correlation coefficient, r =\n",r)
OUTPUT IMAGE