我最初发布下面的基准是为了推荐numpy.corrcoef,愚蠢地没有意识到原始问题已经使用corrcoef并且实际上是在询问更高阶多项式拟合。我已经使用statsmodels为多项式r-squared问题添加了一个实际的解决方案,并且我已经离开了原始的基准测试,这些基准测试虽然偏离主题,但对某些人来说可能是有用的。
statsmodels能够直接计算多项式拟合的r^2,这里有两种方法......
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Construct the columns for the different powers of x
def get_r2_statsmodels(x, y, k=1):
xpoly = np.column_stack([x**i for i in range(k+1)])
return sm.OLS(y, xpoly).fit().rsquared
# Use the formula API and construct a formula describing the polynomial
def get_r2_statsmodels_formula(x, y, k=1):
formula = 'y ~ 1 + ' + ' + '.join('I(x**{})'.format(i) for i in range(1, k+1))
data = {'x': x, 'y': y}
return smf.ols(formula, data).fit().rsquared # or rsquared_adj
为了进一步利用statsmodels,还应该查看拟合的模型摘要,该摘要可以在Jupyter / IPython笔记本中打印或显示为丰富的HTML表格。除了rsquared之外,结果对象还提供对许多有用的统计指标的访问。
model = sm.OLS(