開始使用免費開始

計算共變異數

可以使用 Numpy 的 np.cov() 來計算共變異數。例如,若有兩組資料 xynp.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

編輯並執行程式碼