计算方差
了解常用函数在底层做了什么很重要。即使您已经会计算方差,本课程作为入门课程,并不默认这一点。在本练习中,我们将根据视频中讨论的公式,显式计算 Iris veriscolor 的花瓣长度方差。随后,我们将使用 np.var() 来计算它。
本练习是课程的一部分
Python 中的统计思维(第 1 部分)
练习说明
- 创建名为
differences的数组,它是花瓣长度(versicolor_petal_length)与其均值之间的差。变量versicolor_petal_length已作为 NumPy 数组在您的命名空间中,因此可以利用 NumPy 的向量化运算。 - 将该数组中的每个元素平方。例如,
x**2会对数组x的每个元素求平方。将结果保存为diff_sq。 - 使用
np.mean()计算diff_sq中元素的均值。将结果保存为variance_explicit。 - 使用
np.var()计算versicolor_petal_length的方差。将结果保存为variance_np。 - 在一次
print调用中同时打印variance_explicit和variance_np,以确认两者一致。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Array of differences to mean: differences
# Square the differences: diff_sq
# Compute the mean square difference: variance_explicit
# Compute the variance using NumPy: variance_np
# Print the results