python - 用Python的statsmodels的OLS线性回归进行曲线拟合时,公式中的常数如何选择?

标签 python pandas matplotlib curve-fitting statsmodels

  • 我想将不同程度的线性回归模型拟合到数据集,并根据调整后的 r^2 选择最合适的模型。
  • 基于 other answers ,我正在使用 OLS 公式 "y ~ 1 + "+ "+ ".join("I(x**{})".format(i) for i in range(1, degree+1) ),
  • 我没有足够的统计知识来理解:是否需要 1 + 常量?如果需要,常量值应该是多少?
import numpy
import pandas
import matplotlib
import matplotlib.offsetbox
import statsmodels.tools
import statsmodels.formula.api

data = numpy.array([
  [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.DataFrame(data, columns=["Year", "CrudeRate"])

cause = "Malignant neoplasms"
x = df["Year"].values
y = df["CrudeRate"].values
degree = 2
predict_future_years = 5

# https://stackoverflow.com/a/34617603/4135310
olsdata = {"x": x, "y": y}
formula = "y ~ 1 + " + " + ".join("I(x**{})".format(i) for i in range(1, degree+1))
model = statsmodels.formula.api.ols(formula, olsdata).fit()

print(model.summary())

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

# https://stackoverflow.com/a/37294651/4135310
func = numpy.poly1d(model.params.values[::-1])
matplotlib.pyplot.plot(df["Year"], func(df["Year"]))

predicted = func(df.Year.values[-1] + predict_future_years)
print("Predicted in {} years: {}".format(predict_future_years, predicted))

ax.add_artist(matplotlib.offsetbox.AnchoredText("$\\barR^2$ = {:0.2f}".format(model.rsquared_adj), loc="upper center"))
ax.add_artist(matplotlib.offsetbox.AnchoredText("Predicted in +{} = {:0.2f}".format(predict_future_years, predicted), loc="upper right"))

ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%d"))
fig = matplotlib.pyplot.gcf()
fig.autofmt_xdate(bottom=0.2, rotation=30, ha="right", which="both")
matplotlib.pyplot.tight_layout()
cleaned_title = cause.replace(" ", "_").replace("(", "").replace(")", "")
#matplotlib.pyplot.savefig("{}_{}.png".format(cleaned_title, degree), dpi=100)
matplotlib.pyplot.show()

Figure

最佳答案

根据@ALollz 的评论,当使用 Patsy 符号(例如 statsmodels.formula.api.ols("y ~ x"))时,您不需要需要包含 1 +,因为该常量默认添加到模型中,尽管这并未指定您的模型具有取值为 1 的常量。相反,它指定您有一个常数,其大小将由截距系数给出。这是 OLS 确定的常数,所以它就是您想要的。

关于python - 用Python的statsmodels的OLS线性回归进行曲线拟合时,公式中的常数如何选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582625/

相关文章:

python - 系列列表到数据框

python - Pandas 有没有办法过滤字符串中包含的列中的行

python - pandas 数据透视表 - 导致意外边距的有序类别

python - 如何在箱线图中显示 Pandas DataFrame 的最后一行

python - 是否可以使 matplotlib 图形轴等比例缩放?

python - Pyspark 多 groupby 具有不同的列

python - str没有附加属性错误

python - 在 discord.py 中将引号作为参数传递时出错

python - matplotlib中控制散点图y轴顺序

python - 输入组装在 Camel Case 中的单条线路