共變異數與相關
共變異數用來衡量兩個變數是否會一起變動(「變異」)。它的計算方式是逐點計算先前練習中的偏差乘積 dx[n]*dy[n],再對所有這些乘積取平均。
相關本質上是標準化後的共變異數。在這個練習中,你會拿到兩個高度相關的資料陣列,並將視覺化並計算「共變異數」與「相關」兩者。

本練習屬於課程
Python 線性建模入門
練習說明
- 使用
np.mean()先減去平均數來計算偏差dx與dy,並將它們的乘積dx*dy取平均作為covariance。 - 使用
np.std()以標準差進行除法來計算標準化偏差zx與zy,並將它們的乘積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)