开始使用免费开始使用

使用 Scipy 进行优化

可以用 numpy 编写一个解析解来求最小的 RSS 值。但对于更复杂的模型,往往无法得到解析公式,因此我们需要采用其他方法。

在本练习中,您将使用 scipy.optimize,以一种更通用的方式来求解同一优化问题。

在此过程中,您会看到该方法返回的额外结果,用来回答"最优解有多好"。为便于与新的 scipy 方法进行比较,我们将继续使用上一个练习中的同一组观测数据和参数。

本练习是课程的一部分

Python 线性建模入门

查看课程

练习说明

  • 定义函数 model_func(x, a0, a1),对给定数组 x 返回 a0 + a1*x
  • 使用 scipyoptimize.curve_fit() 计算 a0a1 的最优值。
  • 解包 param_opt,将模型参数保存为 a0 = param_opt[0]a1 = param_opt[1]
  • 使用预定义函数 compute_rss_and_plot_fit 来测试并验证您的答案。

交互式实操练习

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

# Define a model function needed as input to scipy
def model_func(x, a0, a1):
    return ____ + (____*x)

# Load the measured data you want to model
x_data, y_data  = load_data()

# call curve_fit, passing in the model function and data; then unpack the results
param_opt, param_cov = optimize.curve_fit(____, x_data, y_data)
a0 = param_opt[0]  # a0 is the intercept in y = a0 + a1*x
a1 = param_opt[1]  # a1 is the slope     in y = a0 + a1*x

# test that these parameters result in a model that fits the data
fig, rss = compute_rss_and_plot_fit(____, ____)
编辑并运行代码