繁体   English   中英

为什么statsmodels的OLS中的四次线性回归不匹配LibreOffice Calc?

[英]Why doesn't a quartic linear regression in statsmodels' OLS match LibreOffice Calc?

我将Statsmodels的OLS线性回归与Patsy四次公式y〜x y ~ x + I(x**2) + I(x**3) + I(x**4)但所得回归结果与拟合的数据相差甚远到LibreOffice Calc。 为什么这与LibreOffice Calc产生的结果不匹配?

statsmodels代码:

import io
import numpy
import pandas
import matplotlib
import matplotlib.offsetbox
import statsmodels.tools
import statsmodels.formula.api

csv_data = """Year,CrudeRate
1999,197.0
2000,196.5
2001,194.3
2002,193.7
2003,192.0
2004,189.2
2005,189.3
2006,187.6
2007,186.9
2008,186.0
2009,185.0
2010,186.2
2011,185.1
2012,185.6
2013,185.0
2014,185.6
2015,185.4
2016,185.1
2017,183.9
"""

df = pandas.read_csv(io.StringIO(csv_data))

cause = "Malignant neoplasms"
x = df["Year"].values
y = df["CrudeRate"].values

olsdata = {"x": x, "y": y}
formula = "y ~ x + I(x**2) + I(x**3) + I(x**4)"
model = statsmodels.formula.api.ols(formula, olsdata).fit()

print(model.params)

df.plot("Year", "CrudeRate", kind="scatter", grid=True, title="Deaths from {}".format(cause))

func = numpy.poly1d(model.params.values[::-1])
matplotlib.pyplot.plot(df["Year"], func(df["Year"]))

matplotlib.pyplot.show()

产生以下系数:

Intercept    9.091650e-08
x            9.127904e-05
I(x ** 2)    6.109623e-02
I(x ** 3)   -6.059164e-05
I(x ** 4)    1.503399e-08

和下图:

图1

但是,如果我将数据带入LibreOffice Calc,请单击图并选择“插入趋势线...”,选择“多项式”,输入“度数” = 4,然后选择“显示方程式”,结果趋势线为与statsmodels不同,并且看起来更合适:

图2

系数为:

Intercept = 1.35e10
x =          2.69e7
x^2 =       -2.01e4
x^3 =          6.69
x^4 =      -0.83e-3

statsmodels版本:

$ pip3 list | grep statsmodels
statsmodels                  0.9.0

编辑:三次也不匹配,但是二次匹配。

编辑:按比例缩小Year (并在LibreOffice中执行相同操作)匹配项:

df = pandas.read_csv(io.StringIO(csv_data))
df["Year"] = df["Year"] - 1998

缩小后的系数和图:

Intercept    197.762384
x             -0.311548
I(x ** 2)     -0.315944
I(x ** 3)      0.031304
I(x ** 4)     -0.000833

图3

根据@Josef的评论,问题在于大量数字不适用于高阶多项式,而statsmodels不能自动缩放域。 此外,我在原始问题中没有提到这一点,因为我不希望对域进行转换,但是我还需要根据年份来预测样本外值,因此我将其设为范围的结尾:

predict_x = +5
min_scaled_domain = -1
max_scaled_domain = +1
df["Year"] = df["Year"].transform(lambda x: numpy.interp(x, (x.min(), x.max() + predict_x), (min_scaled_domain, max_scaled_domain)))

此转换创建了拟合良好的回归:

图4

如果在LibreOffice Calc中应用了相同的域转换,则系数匹配。

最后,打印预测值:

func = numpy.polynomial.Polynomial(model.params)
print(func(max_scaled_domain))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM