在合适的 Anscombe 数据上做线性回归
为了练习,请对 Anscombe 四重奏中最适合用线性回归解释的数据集执行一次线性回归。
本练习是课程的一部分
Python 统计思维(第 2 部分)
练习说明
- 使用
np.polyfit()计算斜率和截距的参数。Anscombe 数据存放在数组x和y中。 - 打印斜率
a和截距b。 - 从线性回归生成理论的 \(x\) 和 \(y\) 数据。请用
np.array()创建包含3和15的 \(x\) 数组。生成 \(y\) 数据时,用斜率乘以x_theor再加上截距。 - 将 Anscombe 数据绘制为散点图,然后再绘制理论直线。请记得在绘制 Anscombe 散点图时,除了传入
x和y,还需包含关键字参数marker='.'和linestyle='none'。绘制理论直线时不需要这些参数。 - 点击提交即可查看图形!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Perform linear regression: a, b
a, b = ____
# Print the slope and intercept
print(____, ____)
# Generate theoretical x and y data: x_theor, y_theor
x_theor = np.array([____, ____])
y_theor = ____ * ____ + ____
# Plot the Anscombe data and theoretical line
_ = ____
_ = ____
# Label the axes
plt.xlabel('x')
plt.ylabel('y')
# Show the plot
plt.show()