計算共變異數
可以使用 Numpy 的 np.cov() 來計算共變異數。例如,若有兩組資料 x 與 y,np.cov(x, y) 會回傳一個 2D 陣列,其中的 [0,1] 與 [1,0] 項目就是共變異數。[0,0] 是 x 的變異數,[1,1] 是 y 的變異數。這個 2D 輸出陣列稱為「共變異數矩陣」,因為它同時整理了自變異數與共變異數。
為了讓你回想 I. versicolor 的花瓣長度與寬度之間的關係,我們附上你在前一個練習產生的散佈圖。
本練習屬於課程
Statistical Thinking in Python (Part 1)
練習說明
- 使用
np.cov()計算 I. versicolor 的花瓣長度(versicolor_petal_length)與寬度(versicolor_petal_width)之共變異數矩陣。 - 列印共變異數矩陣。
- 從共變異數矩陣的
[0,1]項目擷取共變異數。注意由於對稱性,[1,0]與[0,1]相同。 - 列印共變異數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Compute the covariance matrix: covariance_matrix
# Print covariance matrix
# Extract covariance of length and width of petals: petal_cov
# Print the length/width covariance