线性回归
我们将假设生育率是女性文盲率的线性函数。也就是说,$f = a i + b$,其中 \(a\) 为斜率,\(b\) 为截距。可以把截距理解为最低生育率,大概在 1 到 2 之间。斜率反映了生育率随文盲率的变化情况。我们可以使用 np.polyfit() 来找到最佳拟合直线。
请绘制数据点和最佳拟合直线,并打印斜率与截距。(想一想:它们的单位是什么?)
本练习是课程的一部分
Python 统计思维(第 2 部分)
练习说明
- 使用
np.polyfit()计算回归直线的斜率和截距。请记住,fertility在 y 轴,illiteracy在 x 轴。 - 打印线性回归得到的斜率和截距。
- 为了绘制最佳拟合直线,使用
np.array()创建仅包含 0 和 100 的数组x。然后基于您的回归参数计算理论y值,即y = a * x + b。 - 在同一张图上绘制数据点和回归直线。请务必标注坐标轴。
- 点击提交以显示您的图表。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Plot the illiteracy rate versus fertility
_ = plt.plot(illiteracy, fertility, marker='.', linestyle='none')
plt.margins(0.02)
_ = plt.xlabel('percent illiterate')
_ = plt.ylabel('fertility')
# Perform a linear regression using np.polyfit(): a, b
a, b = ____
# Print the results to the screen
print('slope =', a, 'children per woman / percent illiterate')
print('intercept =', b, 'children per woman')
# Make theoretical line to plot
x = ____
y = ____ * ____ + ____
# Add regression line to your plot
_ = plt.plot(____, ____)
# Draw the plot
plt.show()