开始使用免费开始使用

查看回归的 R-squared

R-squared 衡量数据与回归线的拟合紧密程度,因此在简单回归中,R-squared 与两个变量之间的相关性有关。具体来说,相关性的绝对值等于 R-squared 的平方根,而相关性的符号与回归系数的符号一致。

在本练习中,您将开始使用统计库 statsmodels。它实现了许多在 R 以及 SAS、MATLAB 等软件中常见的统计建模与检验功能。

您将使用两个序列 xy,先计算它们的相关系数,然后使用 statsmodels.api 库中的函数 OLS(y,x)yx 回归(注意,因变量或等号右侧变量 y 是第一个参数)。大多数线性回归都包含一个常数项,即截距(回归 \(\small y_t=\alpha + \beta x_t + \epsilon_t\) 中的 \(\small \alpha\))。要在 OLS() 中包含常数项,您需要在回归的右侧添加一列全为 1 的列。

模块 statsmodels.api 已作为 sm 为您导入。

本练习是课程的一部分

Python 中的时间序列分析

查看课程

练习说明

  • 使用 .corr() 方法计算 xy 的相关系数。
  • 运行一次回归:
    • 先将 Series x 转换为 DataFrame dfx
    • 使用 sm.add_constant() 添加常数列,并将结果赋给 dfx1
    • 使用 sm.OLS().fit()ydfx1 回归。
  • 打印回归结果,并对比 R-squared 与相关系数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import the statsmodels module
import statsmodels.api as sm

# Compute correlation of x and y
correlation = ___
print("The correlation between x and y is %4.2f" %(correlation))

# Convert the Series x to a DataFrame and name the column x
dfx = pd.DataFrame(x, columns=['x'])

# Add a constant to the DataFrame dfx
dfx1 = sm.add_constant(___)

# Regress y on dfx1
result = sm.OLS(___, ___).fit()

# Print out the results and look at the relationship between R-squared and the correlation above
print(result.summary())
编辑并运行代码