开始使用免费开始使用

使用 `numpy` 进行最小二乘

下面的公式来自引言中所讨论的微积分推导。在本练习中,我们将相信该推导是正确的,并使用 numpy 在代码中实现这些公式。

$$ a_{1} = \frac{ covariance(x, y) }{ variance(x) } $$ $$ a_{0} = mean(y) - a_{1} mean(x) $$

本练习是课程的一部分

Python 线性建模入门

查看课程

练习说明

  • 计算预加载数据中两个变量 x, y 的均值和偏差。
  • 使用 np.sum() 完成最小二乘公式,并据此计算 a0a1 的最优值。
  • 使用 model() 基于最优斜率 a1 和截距 a0 构造模型值 y_model
  • 使用预定义的 compute_rss_and_plot_fit() 直观确认该最优模型与数据的拟合效果。

交互式实操练习

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

# prepare the means and deviations of the two variables
x_mean = np.____(x)
y_mean = np.____(y)
x_dev = x - ____
y_dev = y - ____

# Complete least-squares formulae to find the optimal a0, a1
a1 = np.sum(____ * ____) / np.sum( np.square(____) )
a0 = ____ - (a1 * ____)

# Use the those optimal model parameters a0, a1 to build a model
y_model = model(x, ____, ____)

# plot to verify that the resulting y_model best fits the data y
fig, rss = compute_rss_and_plot_fit(a0, a1)
编辑并运行代码