开始使用免费开始使用

使用 `statsmodels` 的最小二乘法

有一些 Python 库提供了便捷的高层抽象接口,帮助您在优化模型时不必每一步都显式处理细节。

在本练习中,您将以一个示例使用 statsmodels 库,按更高层、通用的工作流,通过最小二乘优化(最小化 RSS)来构建模型。

为便于开始,我们已通过 x_data, y_data = load_data() 预加载了数据,并使用 df = pd.DataFrame(dict(x_column=x_data, y_column=y_data)) 将其存入一个 pandas DataFrame,列名为 x_columny_column

本练习是课程的一部分

Python 线性建模入门

查看课程

练习说明

  • 使用公式 formula="y_column ~ x_column" 和数据 data=df 构建 ols() 模型,并对数据调用 .fit()
  • 使用 model_fit.predict() 得到 y_model 值。
  • 使用提供的函数 plot_data_with_model(),将 y_datay_model 叠加绘制。
  • model_fit.params 中提取模型参数 a0a1
  • 使用 compute_rss_and_plot_fit() 来确认这些结果与使用 numpy 实现的解析公式保持一致。

交互式实操练习

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

# Pass data and `formula` into ols(), use and `.fit()` the model to the data
model_fit = ols(____="y_column ~ x_column", ____=df).____()

# Use .predict(df) to get y_model values, then over-plot y_data with y_model
y_model = model_fit.____(df)
fig = plot_data_with_model(x_data, ____, ____)

# Extract the a0, a1 values from model_fit.params
a0 = model_fit.____['Intercept']
a1 = model_fit.____['x_column']

# Visually verify that these parameters a0, a1 give the minimum RSS
fig, rss = compute_rss_and_plot_fit(a0, a1)
编辑并运行代码