В приведенном ниже коде я получаю один и тот же параметр R2
независимо от того, какую степень полинома k
я использую для подгонки данных. Почему это так?
import numpy as np
import numpy.random as rd
import matplotlib
import matplotlib.pyplot as plt
# Variables
rd.seed(1234)
n = 100
noise = rd.normal(0,0.1,n)
## Mock data
x = np.linspace(0,3,n)
y = x**2 + noise
## Fit
k = 2
p, cov = np.polyfit(x, y, k, cov=True) ##
xfit = np.sort(x)
yfit = np.sort(np.polyval(p, xfit))
perr = np.sqrt(np.diag(cov)) # standard-deviation estimates for each coefficient
R2 = np.corrcoef(x, y)[0, 1]**2 # coefficient of determination between x and y
resid = y - yfit
n = y.size ; m = p.size
dof = n - m # degrees of freedom
chi2 = np.sum((resid/yfit)**2) # chi-squared; estimates error in data
chi2red = chi2/(dof) # reduced chi-squared; measures goodness of fit
s_err = np.sqrt(np.sum(resid**2)/(dof)) # standard deviation of the error
print('degree =', k, '\nR2 =', R2, '\nchi2 =', chi2red, '\nserr =', s_err, '\ncoeffs a-c =', p)
## Plot
fig, ax = plt.subplots(figsize=(12,10))
plt.scatter(x, y, s=40, facecolors='', edgecolors='grey')
plt.plot(xfit, yfit, 'r--')
plt.show()
Эти два имеют одинаковые R2
:
![enter image description here](https://i.stack.imgur.com/naKH9.png)