线性回归算法
若要真正理解线性回归,了解其算法如何工作很有帮助。ols() 的代码有数百行,因为它需要适用于任意公式和任意数据集。不过,对于单一数据集的简单线性回归,您只需几行代码就能实现一个线性回归算法。
工作流程如下:
- 首先,编写一个函数来计算平方和,使用如下通用语法:
def function_name(args):
# some calculations with the args
return outcome
- 其次,使用
scipy的最小化函数来找到使该函数最小的系数。
解释变量(taiwan_real_estate 的 n_convenience 列)已作为 x_actual 提供。
响应变量(taiwan_real_estate 的 price_twd_msq 列)已作为 y_actual 提供。
minimize() 也已加载。
本练习是课程的一部分
Python 中级回归:使用 statsmodels
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Complete the function
def calc_sum_of_squares(coeffs):
# Unpack coeffs
____, ____ = ____
# Calculate predicted y-values
y_pred = ____ + ____ * ____
# Calculate differences between y_pred and y_actual
y_diff = ____ - ____
# Calculate sum of squares
sum_sq = ____
# Return sum of squares
return sum_sq
# Test the function with intercept 10 and slope 1
print(calc_sum_of_squares([10, 1]))