拟合方程与决定系数的计算

在研究 RSRS 指标的时候,需要用到方程拟合和结果评估,最常见的评估方法就是使用 R2 来做评分。

使用 Python 做计算的时候,有三种方式可以实现对应的拟合和计算的过程。

Numpy polyfit

对于 numpy.polyfit() 方法,可以直接生成拟合方程,通过调整 deg 参数,可以选择拟合的次数。

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([2,4,6,8,10])

coff = np.polyfit(x, y, deg=1)

fitted_v = np.polyval(coff, x)
print(fitted_v)
poly_r_squared = np.corrcoef(x, fitted_v)[0, 1] ** 2
print(poly_r_squared)
[ 2.  4.  6.  8. 10.]
1.0

statsmodel sm

可以直接调用 statsmodels 方法进行线性拟合,拟合的结果直接符合规则。

import statsmodels.api as sm
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

X = sm.add_constant(x)

model = sm.OLS(y, X).fit()

fitted_values = model.predict(X)
print(fitted_values)

r_squared = model.rsquared
print(r_squared)
[ 2.  4.  6.  8. 10.]
1.0

statsmodels 和 Numpy 进行结合使用

import numpy as np
import statsmodels.api as sm

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

coefficients = np.polyfit(x, y, 1)

X = sm.add_constant(x)

model = sm.OLS(y, X).fit()
poly_fitted_values = np.polyval(coefficients, x)
ols_fitted_values = model.predict(X)
print(poly_fitted_values)
print(ols_fitted_values)

# 计算R平方
poly_r_squared = np.corrcoef(x, poly_fitted_values)[0, 1] ** 2
ols_r_squared = model.rsquared
print(poly_r_squared)
print(ols_r_squared)

[ 2.  4.  6.  8. 10.]
[ 2.  4.  6.  8. 10.]
1.0
1.0

scipy curve_fit

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

def fit_fun(x, a, b):
    return a * x + b

popt, pcov = curve_fit(fit_fun, x)

后面计算地方法与 numpy.polyfit() 类似。