开始使用免费开始使用

协方差 vs 相关系数

协方差用于度量两个变量是否会一起变化("共同变化")。它通过逐点计算上个练习中的偏差乘积 dx[n]*dy[n],然后对所有乘积取平均得到。

相关系数本质上是标准化后的协方差。本练习为您提供了两组高度相关的数据,您将可视化并计算「协方差」和「相关系数」这两者。

本练习是课程的一部分

Python 线性建模入门

查看课程

练习说明

  • 使用 np.mean() 计算均值并相减,得到偏差 dxdy,并将它们的乘积 dx*dy 取平均,得到 covariance(协方差)。
  • 使用 np.std() 计算标准差并相除,得到标准化偏差 zxzy,并将它们的乘积 zx*zy 取平均,得到 correlation(相关系数)。
  • 使用 plot_normalized_deviations(zx, zy) 绘制标准化偏差的乘积,并将图形与相关系数的数值进行直观对照检查。

交互式实操练习

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

# Compute the covariance from the deviations.
dx = x - np.____(x)
dy = y - np.____(y)
covariance = np.____(____ * ____)
print("Covariance: ", covariance)

# Compute the correlation from the normalized deviations.
zx = dx / np.____(x)
zy = dy / np.____(y)
correlation = np.____(____ * ____)
print("Correlation: ", correlation)

# Plot the normalized deviations for visual inspection. 
fig = plot_normalized_deviations(zx, zy)
编辑并运行代码